使用for循环在python中迭代字符串

时间:2017-01-18 05:54:24

标签: python for-loop

为什么这是迭代不起作用?如果在for循环中将单词替换为range(len(words)),则同样有效

n = ["Michael", "Lieberman"]

def join_strings(words):
    result = ""
    for i in words:
        result += words[i]
    return result

print join_strings(n)

3 个答案:

答案 0 :(得分:2)

您的代码。

n = ["Michael", "Lieberman"]

def join_strings(words):
    # words = ["Michael", "Lieberman"]
    result = ""
    for i in words:
        # i = 'Michael' for the first iteration.
        # if you do range(len(words)) then i=0 and words[0] is valid then
        result += words[i] #<--Error! i='Michael' and you can't do words['Michael']
    return result

print join_strings(n)

在列表中连接字符串的Pythonic方法:

print ''.join(n) #Outputs --> MichaelLieberman

答案 1 :(得分:0)

i是字符串值而不是索引。您可以使用enumerate功能:

for index, i in enumerate(words): 
    result += words[index]

或者您可以使用单词本身:

for i in words:
    result += i

性能:

In [14]: timeit.timeit('string_cat', '''def string_cat():
    ...:     rg = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
    ...: 't', 'u', 'v', 'w', 'x', 'y', 'z']
    ...:     st = ''
    ...:     for x in rg: st += x
    ...: ''', number=1000000)
Out[14]: 0.02700495719909668

In [15]: timeit.timeit('string_cat', '''def string_cat():
    ...:     rg = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
    ...: 't', 'u', 'v', 'w', 'x', 'y', 'z']
    ...:     st = ''.join(rg)
    ...: ''', number=1000000)
Out[15]: 0.026237964630126953

答案 2 :(得分:0)

如果您使用for循环:

for i in words:

然后这样做:

result += i

因为我们直接从列表中获取值而不提及任何范围或大小。

如果您使用for循环:

for i in range(len(words)):

然后这样做:

result += words[i]

并且两种情况的输出都是相同的:

MichaelLieberman

有关for循环的更好说明,请参阅: https://www.learnpython.org/en/Loops