如何基于python中的元素合并列表?

时间:2015-10-28 16:02:07

标签: python list

我是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的新手,我发现这有点难以理解,是否有人能指出我解决问题的方向?

3 个答案:

答案 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)

我会用一个函数来做到这一点:

  1. 打开文档
  2. 阅读每一行,将其存储为列表
  3. 将这些[名称,号码]列表中的每一个存储在元列表中
  4. 剖析元数列表并将其排序为字典
  5. 如果您想测试此代码,请执行以下操作:

    1. 将此代码复制/粘贴到文件中
    2. 添加"打印(名称)"到文件的末尾
    3. 运行sort(' yourFile.csv')
    4. #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)