我是python的新手,所以简单的解释将被赞赏:)
我被分配了一个任务,要求我带一个csv文件,有两列,第一列是名字,第二列是分数。使用此数据,我想为csv文件中的每一行创建一个包含此数据的列表。所以看起来应该是这样的:
list1 = [['Bob Smith', '7'],['Bob Smith', '9'],['Bob Smith', '4'],['James Johnson', '3'],['James Johnson', '6']]
我已经设法做到这一点,但是任务要求我将名称和分数组合在一起并将它们放入新的列表中。这应该是它的样子:
List2 = [['Bob Smith', '7', '9', '4'],['James Johnson', '3', '6']]
基本上,它是从具有相同名称的元素中获取所有分数,并将它们组合在一个新列表中。
由于我是python的新手,我发现这有点难以理解,是否有人能指出我解决问题的方向?
答案 0 :(得分:4)
您可以使用字典https://docs.python.org/2/tutorial/datastructures.html#dictionaries)来创建从名称到值列表的映射。例如:
npm install -g ttembed-js
ttembed-js somefont.ttf
打印
import collections
list1 = [
['Bob Smith', '7'],
['Bob Smith', '9'],
['Bob Smith', '4'],
['James Johnson', '3'],
['James Johnson', '6']]
names = collections.defaultdict(list)
for k, v in list1:
names[k].append(v)
print names
答案 1 :(得分:0)
我不确定您是如何从CSV中读取此文件的,但您可以这样做:
with open(r'c:\debug\file.txt', 'r') as f:
lines = [l.strip().split(',') for l in f.readlines()] # convert each line to a python list
names = { l[0] : [l[0]] for l in lines } # create a dictionary mapped to each "name" in the CSV
for l in lines:
names[l[0]].append(l[1])
list2 = names.values()
print list2:
[['James Johnson', '3', '6'], ['Bob Smith', '7', '9', '4']]
答案 2 :(得分:0)
我会用一个函数来做到这一点:
如果您想测试此代码,请执行以下操作:
#Create a function to open and sort through the .csv file
def sort(fileName):
#Open the file
with open(fileName) as file:
#create your first list to hold the information
lists = []
#read each line in the list
for each in file:
#separate each name from its respective number
(name,number) = each.strip().split(',')
#store them both in a second list
#add each "name and number" to the original list
list2 = [name,number]
lists.append(list2)
#create a dictionary to hold your new datasets
names = {}
#checking for the name and numbers previously stated
for name, number in lists:
#if the name isn't already in your dictionary, "names"
#then add it to the dictionary, and its respective number
if name not in names:
names[name] = [number]
#but if the name IS in the dictionary, add the new number to it.
else:
names[name].append(number)