创建一个在Python中按字符分隔的列表

时间:2011-10-09 11:17:36

标签: python list for-loop

我正在尝试使用来自其他词典的数据列出前4个最大值,但我得到的结果会将每个词分成单个字符。完整的代码是:

max_list = []    
MaxSimilarity = 0
for d in year:
    f = FavActorFunction(max_films[c], d)    
    if d != MaxGrossFinder(c):
        if year[d] == c:
            if f > MaxSimilarity:
                MaxSimilarity = f
                max = d
max_list.append(max)

MaxSimilarity2 = 0            
for d in year:
    g = FavActorFunction(max_films[c], d)    
    if d != MaxGrossFinder(c):
        if d != max:
            if year[d] == c:
                if g > MaxSimilarity2:
                    MaxSimilarity2 = g
                    max2 = d
max_list.append(max2)

MaxSimilarity3 = 0            
for d in year:
    h = FavActorFunction(max_films[c], d)    
    if d != MaxGrossFinder(c):
        if d != max and d != max2:
            if year[d] == c:
                if h > MaxSimilarity3:
                    MaxSimilarity3 = h
                    max3 = d
max_list.append(max3)


MaxSimilarity4 = 0            
for d in year:
    i = FavActorFunction(max_films[c], d)    
    if d != MaxGrossFinder(c):
        if d != max and d != max2 and d != max3:
            if year[d] == c:
                if i > MaxSimilarity4:
                    MaxSimilarity4 = i
                    max4 = d
max_list.append(max4)
print max_list

我得到的结果是['3','0','0','T','r','a','n','s','f','o',' r','m','e','r','s','S','p','i','d','e','r',' - ','M' ,'a','n','','3','3','0','0']

如何更改此代码以获取['300',变形金刚等]

1 个答案:

答案 0 :(得分:2)

您的函数FavActorFunction似乎返回的是字符列表而不是单词列表。

如果迭代字符串,而不是迭代字符串的列表,就会发生这种情况。例如,请注意将字符串转换为列表时会发生什么:

>>> print list("Hello, world")
print list("Hello, world")
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']

由于您刚刚学习,请考虑以下建议:使用描述性变量名称。 dchg等名称几乎无法理解您的代码。使用actordirector等变量。你不会因为简洁而获得奖励积分(除非你有一个糟糕的教练)。