如何附加包含新数据的列表?

时间:2015-11-19 21:10:15

标签: python list

我从csv文件中读取信息并将其转换为python中的列表列表,如下所示:

[['a', '1', '2', '3'],
['b', '7', '8', '1'],
['c', '0', '10', '1'],
['d', '7', '8', '3'],
['e', '9', '8', '2']]

然后我获得包含d的列表的新输入。新值为5。 知道要编辑的元素我只想更改d - 列表中包含的最后一个元素,并将其替换为新值(将3替换为5)。

所以我想在列表中找到包含d的子列表,并根据需要进行编辑,给出:

[['a', '1', '2', '3'],
['b', '7', '8', '1'],
['c', '0', '10', '1'],
['d', '8', '3', '5'],
['e', '9', '8', '2']]

删除第一个号码并添加新号码:

import csv, re

name = input("Name: ").title()
data = [name]
for x in range(1,4):
    score = int(input("What score? "))
    data.append(score)
form = input("What form: 1,2 or 3? ")

print(data)

with open('{}.csv'.format(form), 'a', newline='') as csvfile:
    wr = csv.writer(csvfile)
    wr.writerow(data)

f = open('{}.csv'.format(form))
csv_f = csv.reader(f)

newlist = []

for row in csv_f:
    newlist.append(row[0:4])

print(newlist)

1 个答案:

答案 0 :(得分:0)

看看这是否解决了您的问题

%put 'An error occurred on line ' &LINE_NO;

,输入文件为

import csv
from collections import defaultdict

with open("file.csv") as f:
    csvfile = csv.reader(f)
    names = defaultdict(list)
    for row in csvfile:
        curname = row[0]
        new_nums = row[1:4]
        name_nums = names.get(curname)
        if name_nums:
            del name_nums[:len(new_nums)]
        names[curname].extend(new_nums)

print(names)

生成包含<{p}}的John,1,2,3 Mary,1,2,3 John,4,5

defaultdict

正如下面的评论所指出的,这里有一个产生普通字典

的替代方案
{
 'John': ['3', '4', '5'],
 'Mary': ['1', '2', '3']
}

注意:从输入数据中可以看出,给定的解决方案适用于任何给定数量的新值(指定最多三个,但您可以更改它),而不仅仅是一个(即import csv with open("file.csv") as f: csvfile = csv.reader(f) names = dict() for row in csvfile: curname = row[0] # get the name on first col new_nums = row[1:4] # get the values as a list name_nums = names.get(curname) # get the stored values for the name if name_nums: # true when the name had been encountered already del name_nums[:len(new_nums)] # pop as many values as the new ones name_nums.extend(new_nums) # append the new values else: names[curname] = new_nums # new name so just add it to the dict print(names) in你的例子)