简体   繁体   English

Python:附加列表实际上并没有附加它?

[英]Python: Appending a list doesn't actually append it?

I have a CSV file with names and scores in it.我有一个包含名称和分数的 CSV 文件。 I've made each line a separate list but when appending a variable to this list it doesn't actually do it.我已经将每一行作为一个单独的列表,但是当将一个变量附加到这个列表时,它实际上并没有这样做。 My code is:我的代码是:

import csv
f = open('1scores.csv')
csv_f = csv.reader(f)
newlist = []
for row in csv_f:
    newlist.append(row[0:4])

    minimum = min(row[1:4])
    newlist.append(minimum)
print(newlist)

With the data in the file being随着文件中的数据

Person One,4,7,4
Person Two,1,4,2
Person Three,3,4,1
Person Four,2

Surely the output would be ['Person One', '4', '7', '4', '4'] as the minimum is 4, which I'm appending to the list.当然输出将是['Person One', '4', '7', '4', '4']因为最小值是 4,我将其附加到列表中。 But I get this: ['Person One', '4', '7', '4'], '4', What am I doing wrong?但我明白了: ['Person One', '4', '7', '4'], '4',我做错了什么? I want the minimum to be inside the list, instead of outside but don't understand.我希望最小值在列表内,而不是在列表外,但不明白。

Append the min to each row and then append the row itself, you are appending the list you slice first then adding the min value to newlist not to the sliced list:将最小值附加到每一行,然后附加行本身,您先附加切片的列表,然后将最小值添加到 newlist 而不是切片列表:

for row in csv_f:
    row.append(min(row[1:],key=int)
    newlist.append(row)

You could also use a list comp:您还可以使用列表组件:

new_list =  [row + [min(row[1:], key=int)] for row in csv_f]

You also need the, key=int or you might find you get strange results as your scores/strings will be compared lexicographically:您还需要key=int否则您可能会发现得到奇怪的结果,因为您的分数/字符串将按字典顺序进行比较:

In [1]: l = ["100" , "2"] 

In [2]: min(l)
Out[2]: '100'

In [3]: min(l,key=int)
Out[3]: '2'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM