Hướng dẫn how to replace for loop in python - cách thay thế vòng lặp for trong python

Đã muộn và tôi đã cố gắng làm việc trên một tập lệnh đơn giản để đổi tên Point Cloud Data thành một định dạng hoạt động. Tôi không biết tôi đang làm gì sai vì mã ở phía dưới hoạt động tốt. Tại sao mã không có trong công việc vòng lặp? Nó đang thêm nó vào danh sách nhưng nó không được định dạng bởi hàm thay thế. Xin lỗi tôi biết đây không phải là một trình gỡ lỗi nhưng tôi thực sự bị mắc kẹt về điều này và có lẽ sẽ mất 2 giây để người khác thấy vấn đề.

Show
# Opening and Loading the text file then sticking its lines into a list []
filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
lines = text.readlines()
linesNew = []
temp = None


# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp.replace(' ', ', ',2)
    linesNew.append(temp)


# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)


text.close()

Đã hỏi ngày 18 tháng 10 năm 2011 lúc 23:34Oct 18, 2011 at 23:34

SacredgeometrysacredgeometrySacredGeometry

8364 Huy hiệu vàng13 Huy hiệu bạc24 Huy hiệu đồng4 gold badges13 silver badges24 bronze badges

Bạn không gán giá trị trả về của

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
3 cho bất cứ điều gì. Ngoài ra,
# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
4 và
# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
5 là không cần thiết.

Thử cái này:

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()

Đã trả lời ngày 18 tháng 10 năm 2011 lúc 23:37Oct 18, 2011 at 23:37

Hướng dẫn how to replace for loop in python - cách thay thế vòng lặp for trong python

0

Chuỗi là bất biến.

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
6 Trả về một chuỗi mới, đó là những gì bạn phải chèn vào danh sách
# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
7.

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)

Đã trả lời ngày 18 tháng 10 năm 2011 lúc 23:37Oct 18, 2011 at 23:37

Chuỗi là bất biến.

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
6 Trả về một chuỗi mới, đó là những gì bạn phải chèn vào danh sách
# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
7.Nathan

Nathannathan1 gold badge28 silver badges35 bronze badges

4.5851 Huy hiệu vàng28 Huy hiệu bạc35 Huy hiệu đồng

Tôi đã có một vấn đề tương tự và đã đưa ra mã dưới đây để giúp giải quyết nó. Vấn đề cụ thể của tôi là tôi cần trao đổi một số phần nhất định của một chuỗi với nhãn tương ứng. Tôi cũng muốn một cái gì đó có thể tái sử dụng ở những nơi khác nhau trong ứng dụng của tôi.

>>> string = "Let's take a trip to Paris next January"
>>> lod = [{'city':'Paris'}, {'month':'January'}]
>>> processed = TextLabeler(string, lod)
>>> processed.text
>>> Let's take a trip to [[ city ]] next [[ month ]]

Với mã bên dưới, tôi có thể làm như sau:

class TextLabeler():
    def __init__(self, text, lod):
        self.text = text
        self.iterate(lod)

    def replace_kv(self, _dict):
        """Replace any occurrence of a value with the key"""

        for key, value in _dict.iteritems():
            label = """[[ {0} ]]""".format(key)
            self.text = self.text.replace(value, label)
            return self.text

    def iterate(self, lod):
        """Iterate over each dict object in a given list of dicts, `lod` """

        for _dict in lod:
            self.text = self.replace_kv(_dict)
        return self.text

Đây là tất cả các mã:Apr 2, 2016 at 4:15

Hướng dẫn how to replace for loop in python - cách thay thế vòng lặp for trong python

Đã trả lời ngày 2 tháng 4 năm 2016 lúc 4:15Joe Fusaro

Joe Fusarojoe Fusaro1 gold badge10 silver badges21 bronze badges

Chức năng: Bản đồ Xem mã trên GIST. Như chúng ta có thể thấy trong hình, chức năng bản đồ tích hợp nhanh hơn nhiều so với vòng lặp for-in. Nói chính xác, nó nhanh hơn 1,63 lần. Không có nghi ngờ rằng chúng ta nên sử dụng chức năng bản đồ tích hợp.

Tôi là một fan hâm mộ của Zen of Python, trong đó nói

Nên có một - và tốt nhất là chỉ một - cách rõ ràng để làm điều đó.

Nhưng trong Python, trên thực tế có nhiều cách để đạt được mục tiêu tương tự. Tất nhiên, một số cách thanh lịch hơn những cách khác và trong hầu hết các trường hợp, rõ ràng là cách nào tốt hơn.list comprehensions, and how they can replace for loops,

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
8 and
# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
9 to create powerful functionality within a single line of Python code.

Chúng tôi sẽ xem xét các toàn bộ danh sách và cách chúng có thể thay thế cho các vòng lặp, # This bloody for loop is the problem for i in lines: temp = str(i) temp2 = temp.replace(' ', ', ',2) linesNew.append(temp2) 8 và # This bloody for loop is the problem for i in lines: temp = str(i) temp2 = temp.replace(' ', ', ',2) linesNew.append(temp2) 9 để tạo chức năng mạnh mẽ trong một dòng mã Python.

Danh sách cơ bản Hiểu

numbers = []
for i in range(1, 11):
    numbers.append(i)

Nhập chế độ FullScreenen EXIT Mode FullScreen

Nói rằng tôi muốn tạo một danh sách các số từ 1 đến 10. Tôi có thể làm

>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Nhập chế độ FullScreenen EXIT Mode FullScreen

và tôi sẽ nhận được

>>> numbers = [i for i in range(1, 11)]
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Nhập chế độ FullScreenen EXIT Mode FullScreen

Nhưng sử dụng danh sách hiểu, điều này có thể được thực hiện trong một dòng

Đây là cú pháp cơ bản của sự hiểu biết danh sách: >>> string = "Let's take a trip to Paris next January" >>> lod = [{'city':'Paris'}, {'month':'January'}] >>> processed = TextLabeler(string, lod) >>> processed.text >>> Let's take a trip to [[ city ]] next [[ month ]] 0. Ở đây, có thể đi được là >>> string = "Let's take a trip to Paris next January" >>> lod = [{'city':'Paris'}, {'month':'January'}] >>> processed = TextLabeler(string, lod) >>> processed.text >>> Let's take a trip to [[ city ]] next [[ month ]] 1, phần tử là >>> string = "Let's take a trip to Paris next January" >>> lod = [{'city':'Paris'}, {'month':'January'}] >>> processed = TextLabeler(string, lod) >>> processed.text >>> Let's take a trip to [[ city ]] next [[ month ]] 2 và biểu thức là >>> string = "Let's take a trip to Paris next January" >>> lod = [{'city':'Paris'}, {'month':'January'}] >>> processed = TextLabeler(string, lod) >>> processed.text >>> Let's take a trip to [[ city ]] next [[ month ]] 2. Điều này tương đương với vòng lặp cho vòng lặp mà chúng tôi đã sử dụng trước đó: chúng tôi thêm >>> string = "Let's take a trip to Paris next January" >>> lod = [{'city':'Paris'}, {'month':'January'}] >>> processed = TextLabeler(string, lod) >>> processed.text >>> Let's take a trip to [[ city ]] next [[ month ]] 2 vào danh sách trong đó >>> string = "Let's take a trip to Paris next January" >>> lod = [{'city':'Paris'}, {'month':'January'}] >>> processed = TextLabeler(string, lod) >>> processed.text >>> Let's take a trip to [[ city ]] next [[ month ]] 2 là một số từ 1 đến 11.

bản đồ()

Hàm

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
8 thường được sử dụng để áp dụng một hàm trên mỗi phần tử trong một điều khác. Truyền trong một hàm và một điều khác nhau, và
# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
8 sẽ tạo ra một đối tượng chứa kết quả chuyển từng phần tử vào hàm.

squares = []
for num in numbers:
    squares.append(num ** 2)

Nhập chế độ FullScreenen EXIT Mode FullScreen

Ví dụ, giả sử tôi muốn tạo một danh sách các ô vuông từ danh sách

>>> string = "Let's take a trip to Paris next January"
>>> lod = [{'city':'Paris'}, {'month':'January'}]
>>> processed = TextLabeler(string, lod)
>>> processed.text
>>> Let's take a trip to [[ city ]] next [[ month ]]
8 mà chúng tôi đã tạo trước đó. Chúng tôi có thể làm

>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Nhập chế độ FullScreenen EXIT Mode FullScreen

Và chúng tôi sẽ nhận được

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()
0

Nhập chế độ FullScreenen EXIT Mode FullScreen

Hoặc chúng ta có thể sử dụng

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
8 như vậy

Ở đây, chúng tôi chuyển từng phần tử trong >>> string = "Let's take a trip to Paris next January" >>> lod = [{'city':'Paris'}, {'month':'January'}] >>> processed = TextLabeler(string, lod) >>> processed.text >>> Let's take a trip to [[ city ]] next [[ month ]] 8 vào hàm Lambda (đây chỉ là một cách dễ dàng để tạo ra các chức năng nếu bạn lười biếng). Đầu ra của việc đặt mỗi số class TextLabeler(): def __init__(self, text, lod): self.text = text self.iterate(lod) def replace_kv(self, _dict): """Replace any occurrence of a value with the key""" for key, value in _dict.iteritems(): label = """[[ {0} ]]""".format(key) self.text = self.text.replace(value, label) return self.text def iterate(self, lod): """Iterate over each dict object in a given list of dicts, `lod` """ for _dict in lod: self.text = self.replace_kv(_dict) return self.text 1 vào hàm class TextLabeler(): def __init__(self, text, lod): self.text = text self.iterate(lod) def replace_kv(self, _dict): """Replace any occurrence of a value with the key""" for key, value in _dict.iteritems(): label = """[[ {0} ]]""".format(key) self.text = self.text.replace(value, label) return self.text def iterate(self, lod): """Iterate over each dict object in a given list of dicts, `lod` """ for _dict in lod: self.text = self.replace_kv(_dict) return self.text 2 sẽ là bình phương của số. Sử dụng class TextLabeler(): def __init__(self, text, lod): self.text = text self.iterate(lod) def replace_kv(self, _dict): """Replace any occurrence of a value with the key""" for key, value in _dict.iteritems(): label = """[[ {0} ]]""".format(key) self.text = self.text.replace(value, label) return self.text def iterate(self, lod): """Iterate over each dict object in a given list of dicts, `lod` """ for _dict in lod: self.text = self.replace_kv(_dict) return self.text 3, chúng tôi biến đối tượng bản đồ thành một danh sách.

Thay thế bản đồ () bằng danh sách hiểu

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()
1

Nhập chế độ FullScreenen EXIT Mode FullScreen

Sử dụng danh sách hiểu, chúng tôi chỉ có thể làm

Điều này sẽ chuyển từng số class TextLabeler(): def __init__(self, text, lod): self.text = text self.iterate(lod) def replace_kv(self, _dict): """Replace any occurrence of a value with the key""" for key, value in _dict.iteritems(): label = """[[ {0} ]]""".format(key) self.text = self.text.replace(value, label) return self.text def iterate(self, lod): """Iterate over each dict object in a given list of dicts, `lod` """ for _dict in lod: self.text = self.replace_kv(_dict) return self.text 4 vào biểu thức class TextLabeler(): def __init__(self, text, lod): self.text = text self.iterate(lod) def replace_kv(self, _dict): """Replace any occurrence of a value with the key""" for key, value in _dict.iteritems(): label = """[[ {0} ]]""".format(key) self.text = self.text.replace(value, label) return self.text def iterate(self, lod): """Iterate over each dict object in a given list of dicts, `lod` """ for _dict in lod: self.text = self.replace_kv(_dict) return self.text 5 và tạo một danh sách mới trong đó các phần tử chỉ đơn giản là hình vuông của mỗi số trong >>> string = "Let's take a trip to Paris next January" >>> lod = [{'city':'Paris'}, {'month':'January'}] >>> processed = TextLabeler(string, lod) >>> processed.text >>> Let's take a trip to [[ city ]] next [[ month ]] 8.

lọc()

Hàm

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
9 được sử dụng để tạo một tập hợp con của một danh sách hiện có, dựa trên một điều kiện. Truyền trong một hàm và một điều khác nhau, và
# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
9 sẽ tạo ra một đối tượng chứa tất cả các yếu tố trong đó hàm đánh giá thành
class TextLabeler():
    def __init__(self, text, lod):
        self.text = text
        self.iterate(lod)

    def replace_kv(self, _dict):
        """Replace any occurrence of a value with the key"""

        for key, value in _dict.iteritems():
            label = """[[ {0} ]]""".format(key)
            self.text = self.text.replace(value, label)
            return self.text

    def iterate(self, lod):
        """Iterate over each dict object in a given list of dicts, `lod` """

        for _dict in lod:
            self.text = self.replace_kv(_dict)
        return self.text
9.

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()
2

Nhập chế độ FullScreenen EXIT Mode FullScreen

Và chúng tôi sẽ nhận được

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()
3

Nhập chế độ FullScreenen EXIT Mode FullScreen

Hoặc chúng ta có thể sử dụng

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
9 như vậy

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()
4

Nhập chế độ FullScreenen EXIT Mode FullScreen

Ở đây, tất cả các số sẽ được chuyển vào hàm Lambda và nếu

numbers = []
for i in range(1, 11):
    numbers.append(i)
2 là
class TextLabeler():
    def __init__(self, text, lod):
        self.text = text
        self.iterate(lod)

    def replace_kv(self, _dict):
        """Replace any occurrence of a value with the key"""

        for key, value in _dict.iteritems():
            label = """[[ {0} ]]""".format(key)
            self.text = self.text.replace(value, label)
            return self.text

    def iterate(self, lod):
        """Iterate over each dict object in a given list of dicts, `lod` """

        for _dict in lod:
            self.text = self.replace_kv(_dict)
        return self.text
9, số sẽ được đưa vào
numbers = []
for i in range(1, 11):
    numbers.append(i)
4. Tương tự như vậy, nếu
numbers = []
for i in range(1, 11):
    numbers.append(i)
5 là
class TextLabeler():
    def __init__(self, text, lod):
        self.text = text
        self.iterate(lod)

    def replace_kv(self, _dict):
        """Replace any occurrence of a value with the key"""

        for key, value in _dict.iteritems():
            label = """[[ {0} ]]""".format(key)
            self.text = self.text.replace(value, label)
            return self.text

    def iterate(self, lod):
        """Iterate over each dict object in a given list of dicts, `lod` """

        for _dict in lod:
            self.text = self.replace_kv(_dict)
        return self.text
9, số lượng sẽ được bao gồm trong
numbers = []
for i in range(1, 11):
    numbers.append(i)
7.

Thay thế bộ lọc () bằng danh sách hiểu

Sử dụng danh sách hiểu, chúng tôi chỉ có thể làm

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()
5

Nhập chế độ FullScreenen EXIT Mode FullScreen

Ở đây, chúng tôi đang sử dụng một điều kiện. Cú pháp cho điều này là

numbers = []
for i in range(1, 11):
    numbers.append(i)
8. Điều này tương đương với vòng lặp cho vòng lặp mà chúng tôi đã sử dụng trước đó - nếu điều kiện
numbers = []
for i in range(1, 11):
    numbers.append(i)
9 được đáp ứng,
class TextLabeler():
    def __init__(self, text, lod):
        self.text = text
        self.iterate(lod)

    def replace_kv(self, _dict):
        """Replace any occurrence of a value with the key"""

        for key, value in _dict.iteritems():
            label = """[[ {0} ]]""".format(key)
            self.text = self.text.replace(value, label)
            return self.text

    def iterate(self, lod):
        """Iterate over each dict object in a given list of dicts, `lod` """

        for _dict in lod:
            self.text = self.replace_kv(_dict)
        return self.text
4 sẽ được thêm vào
numbers = []
for i in range(1, 11):
    numbers.append(i)
4 và
class TextLabeler():
    def __init__(self, text, lod):
        self.text = text
        self.iterate(lod)

    def replace_kv(self, _dict):
        """Replace any occurrence of a value with the key"""

        for key, value in _dict.iteritems():
            label = """[[ {0} ]]""".format(key)
            self.text = self.text.replace(value, label)
            return self.text

    def iterate(self, lod):
        """Iterate over each dict object in a given list of dicts, `lod` """

        for _dict in lod:
            self.text = self.replace_kv(_dict)
        return self.text
4 là một yếu tố trong
>>> string = "Let's take a trip to Paris next January"
>>> lod = [{'city':'Paris'}, {'month':'January'}]
>>> processed = TextLabeler(string, lod)
>>> processed.text
>>> Let's take a trip to [[ city ]] next [[ month ]]
8 có thể.

Toàn bộ lồng nhau

Nói rằng chúng tôi muốn tạo một ma trận. Điều này sẽ liên quan đến việc tạo ra danh sách lồng nhau. Sử dụng một vòng lặp cho vòng lặp, chúng ta có thể thực hiện như saunested lists. Using a for loop, we can do the following

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()
6

Nhập chế độ FullScreenen EXIT Mode FullScreen

Và chúng tôi sẽ nhận được

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()
7

Nhập chế độ FullScreenen EXIT Mode FullScreen

Hoặc chúng ta có thể sử dụng

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
9 như vậynested comprehension, we could simply do

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()
8

Nhập chế độ FullScreenen EXIT Mode FullScreen

Ở đây, tất cả các số sẽ được chuyển vào hàm Lambda và nếu

numbers = []
for i in range(1, 11):
    numbers.append(i)
2 là
class TextLabeler():
    def __init__(self, text, lod):
        self.text = text
        self.iterate(lod)

    def replace_kv(self, _dict):
        """Replace any occurrence of a value with the key"""

        for key, value in _dict.iteritems():
            label = """[[ {0} ]]""".format(key)
            self.text = self.text.replace(value, label)
            return self.text

    def iterate(self, lod):
        """Iterate over each dict object in a given list of dicts, `lod` """

        for _dict in lod:
            self.text = self.replace_kv(_dict)
        return self.text
9, số sẽ được đưa vào
numbers = []
for i in range(1, 11):
    numbers.append(i)
4. Tương tự như vậy, nếu
numbers = []
for i in range(1, 11):
    numbers.append(i)
5 là
class TextLabeler():
    def __init__(self, text, lod):
        self.text = text
        self.iterate(lod)

    def replace_kv(self, _dict):
        """Replace any occurrence of a value with the key"""

        for key, value in _dict.iteritems():
            label = """[[ {0} ]]""".format(key)
            self.text = self.text.replace(value, label)
            return self.text

    def iterate(self, lod):
        """Iterate over each dict object in a given list of dicts, `lod` """

        for _dict in lod:
            self.text = self.replace_kv(_dict)
        return self.text
9, số lượng sẽ được bao gồm trong
numbers = []
for i in range(1, 11):
    numbers.append(i)
7.

Thay thế bộ lọc () bằng danh sách hiểu

Sử dụng danh sách hiểu, chúng tôi chỉ có thể làm

filename = "/Users/sacredgeometry/Desktop/data.txt"
text = open(filename, 'r')
linesNew = []

for line in text:
    # i is already a string, no need to str it
    # temp = str(i)

    # also, just append the result of the replace to linesNew:
    linesNew.append(line.replace(' ', ', ', 2))

# DEBUGGING THE CODE    
print(linesNew[0])
print(linesNew[1])

# Another test to check that the replace works ... It does!
test2 = linesNew[0].replace(' ', ', ',2)
test2 = test2.replace('\t', ', ')
print('Proof of Concept: ' + '\n' + test2)  

text.close()
9

Nhập chế độ FullScreenen EXIT Mode FullScreen

Và chúng tôi sẽ nhận được

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
0

Nhập chế độ FullScreenen EXIT Mode FullScreen

Hoặc chúng ta có thể sử dụng

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
9 như vậy

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
1

Nhập chế độ FullScreenen EXIT Mode FullScreen

Ở đây, tất cả các số sẽ được chuyển vào hàm Lambda và nếu

numbers = []
for i in range(1, 11):
    numbers.append(i)
2 là
class TextLabeler():
    def __init__(self, text, lod):
        self.text = text
        self.iterate(lod)

    def replace_kv(self, _dict):
        """Replace any occurrence of a value with the key"""

        for key, value in _dict.iteritems():
            label = """[[ {0} ]]""".format(key)
            self.text = self.text.replace(value, label)
            return self.text

    def iterate(self, lod):
        """Iterate over each dict object in a given list of dicts, `lod` """

        for _dict in lod:
            self.text = self.replace_kv(_dict)
        return self.text
9, số sẽ được đưa vào
numbers = []
for i in range(1, 11):
    numbers.append(i)
4. Tương tự như vậy, nếu
numbers = []
for i in range(1, 11):
    numbers.append(i)
5 là
class TextLabeler():
    def __init__(self, text, lod):
        self.text = text
        self.iterate(lod)

    def replace_kv(self, _dict):
        """Replace any occurrence of a value with the key"""

        for key, value in _dict.iteritems():
            label = """[[ {0} ]]""".format(key)
            self.text = self.text.replace(value, label)
            return self.text

    def iterate(self, lod):
        """Iterate over each dict object in a given list of dicts, `lod` """

        for _dict in lod:
            self.text = self.replace_kv(_dict)
        return self.text
9, số lượng sẽ được bao gồm trong
numbers = []
for i in range(1, 11):
    numbers.append(i)
7.

# This bloody for loop is the problem
for i in lines:
    temp = str(i)
    temp2 = temp.replace(' ', ', ',2)
    linesNew.append(temp2)
2

Nhập chế độ FullScreenen EXIT Mode FullScreen

Thay thế bộ lọc () bằng danh sách hiểu

  • Sử dụng danh sách hiểu, chúng tôi chỉ có thể làm
  • Ở đây, chúng tôi đang sử dụng một điều kiện. Cú pháp cho điều này là
    numbers = []
    for i in range(1, 11):
        numbers.append(i)
    
    8. Điều này tương đương với vòng lặp cho vòng lặp mà chúng tôi đã sử dụng trước đó - nếu điều kiện
    numbers = []
    for i in range(1, 11):
        numbers.append(i)
    
    9 được đáp ứng,
    class TextLabeler():
        def __init__(self, text, lod):
            self.text = text
            self.iterate(lod)
    
        def replace_kv(self, _dict):
            """Replace any occurrence of a value with the key"""
    
            for key, value in _dict.iteritems():
                label = """[[ {0} ]]""".format(key)
                self.text = self.text.replace(value, label)
                return self.text
    
        def iterate(self, lod):
            """Iterate over each dict object in a given list of dicts, `lod` """
    
            for _dict in lod:
                self.text = self.replace_kv(_dict)
            return self.text
    
    4 sẽ được thêm vào
    numbers = []
    for i in range(1, 11):
        numbers.append(i)
    
    4 và
    class TextLabeler():
        def __init__(self, text, lod):
            self.text = text
            self.iterate(lod)
    
        def replace_kv(self, _dict):
            """Replace any occurrence of a value with the key"""
    
            for key, value in _dict.iteritems():
                label = """[[ {0} ]]""".format(key)
                self.text = self.text.replace(value, label)
                return self.text
    
        def iterate(self, lod):
            """Iterate over each dict object in a given list of dicts, `lod` """
    
            for _dict in lod:
                self.text = self.replace_kv(_dict)
            return self.text
    
    4 là một yếu tố trong
    >>> string = "Let's take a trip to Paris next January"
    >>> lod = [{'city':'Paris'}, {'month':'January'}]
    >>> processed = TextLabeler(string, lod)
    >>> processed.text
    >>> Let's take a trip to [[ city ]] next [[ month ]]
    
    8 có thể.
  • Toàn bộ lồng nhau

Nói rằng chúng tôi muốn tạo một ma trận. Điều này sẽ liên quan đến việc tạo ra danh sách lồng nhau. Sử dụng một vòng lặp cho vòng lặp, chúng ta có thể thực hiện như sau

Sử dụng sự hiểu biết lồng nhau, chúng ta có thể làm

Danh sách bên ngoài Hiểu

>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4 tạo 5 hàng, trong khi danh sách bên trong hiểu
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
5 tạo 5 cột.

Sự hiểu biết từ điển

Bạn cũng có thể sử dụng sự hiểu biết từ điển. Ví dụ: nếu tôi muốn tạo một từ điển ánh xạ từng số trong

>>> string = "Let's take a trip to Paris next January"
>>> lod = [{'city':'Paris'}, {'month':'January'}]
>>> processed = TextLabeler(string, lod)
>>> processed.text
>>> Let's take a trip to [[ city ]] next [[ month ]]
8 vào hình vuông tương ứng của chúng, chúng ta có thể làm

Điều gì có thể thay thế một vòng lặp?

Thay thế 4: Bản đồ. Ví dụ trường hợp sử dụng bản đồ. Để thực hiện vòng lặp của bản đồ. ....
Thay thế 5: Giảm. Ví dụ trường hợp sử dụng giảm. Để thực hiện vòng lặp giảm. ....
Thay thế 6: Foreach. Ví dụ trường hợp sử dụng foreach. Để thực hiện vòng lặp của foreach. ....
Phương pháp chuỗi. Trường hợp ví dụ Chuỗi bộ lọc, bản đồ, giảm ..

Có khác cho Loop trong Python không?

Nhưng Python cũng cho phép chúng tôi sử dụng điều kiện khác với các vòng lặp. Khối khác chỉ sau khi/trong khi chỉ được thực thi khi vòng lặp không bị chấm dứt bởi một câu lệnh break.Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated by a break statement.

Điều gì nhanh hơn A For Loop Python?

Một cách nhanh hơn để lặp trong Python là sử dụng các chức năng tích hợp.Trong ví dụ của chúng tôi, chúng tôi có thể thay thế vòng lặp cho chức năng tổng.Hàm này sẽ tổng hợp các giá trị bên trong phạm vi số.Mã trên mất 0,84 giây.using built-in functions. In our example, we could replace the for loop with the sum function. This function will sum the values inside the range of numbers. The code above takes 0.84 seconds.

Bản đồ có tốt hơn so với vòng lặp không?

Chức năng: Bản đồ Xem mã trên GIST.Như chúng ta có thể thấy trong hình, chức năng bản đồ tích hợp nhanh hơn nhiều so với vòng lặp for-in.Nói chính xác, nó nhanh hơn 1,63 lần.Không có nghi ngờ rằng chúng ta nên sử dụng chức năng bản đồ tích hợp.