所以我在做输入/输出,我试图弄清楚我的程序的逻辑,即给定名称和类(class),我会按字母顺序将名称写入文件,然后是他们参加的类(class)。我完成了这一点,并将所有内容写入进度中的一个 d 列表中。现在我正在尝试写入一个文本文件“名称,类别,.....(如果多个类别)”
但由于我已将其放入一维列表中,程序会逐项写入,而不是一起摸索名称和类。例如,我想要读取新文件
Ashley,MATH 1426,PHYS 1443
Jonathan,IE 3312
Joseph,IE 3312
Nang,MATH 1426
Ram,IE 3312
Randal,IE 3301,MATH 2325,PHYS 1443
Sol,IE 3301
如果我有一个 d 列表,我该如何执行此操作。我正在考虑写一些类似的东西
while name, remains the same, write the classes, when name changes print newline....., write name and classes
问题在于它是一个单独的列表,我不确定如何检测名称更改。有没有办法将其转换为 2dlist,每个子列表包含一个名称及其类?这是我原始的未组织形式的二维列表,
[['Adam', 'PHYS 1443'], ['Ashley', 'IE 3312'], ['Ashley', 'PHYS 1443'], ['August', 'PHYS 1444'], ['Baron', 'PHYS 1443'], ['Christopher', 'IE 3301'], ['Christopher', 'CSE 1320'], ['Christopher', 'PHYS 1443'], ['Dylan', 'CSE 1310'], ['Henry', 'PHYS 1444'], ['James', 'IE 3301'], ['James', 'PHYS 1443'], ['Jonathan', 'IE 3312'], ['Krishna', 'CSE 1310'], ['Luis', 'CSE 1310'], ['Michael', 'IE 3301'], ['Nang', 'PHYS 1443'], ['Pramod', 'PHYS 1444'], ['Pramod', 'PHYS 1443'], ['Saroj', 'IE 3301'], ['Saroj', 'MATH 1426'], ['Sol', 'CSE 1310'], ['Timothy', 'MATH 2325'], ['Timothy', 'IE 3301']]
为了组织我编写了以下代码,将其附加到一个列表中,这是一个错误
d = []
size = len(c)
two = []
d.append(c[0][0])
d.append(c[0][1])
i = 1
while i < size :
# if current name = previous name, add classes
if c[i][0]==c[i-1][0] :
d.append(c[i][1])
# if current name != previous name, add name and classes
if c[i][0]!= c[i-1][0] :
d.append(c[i][0])
d.append(c[i][1])
i = i + 1
输出为
['Adam', 'PHYS 1443', 'Ashley', 'IE 3312', 'PHYS 1443', 'August', 'PHYS 1444', 'Baron', 'PHYS 1443', 'Christopher', 'IE 3301', 'CSE 1320', 'PHYS 1443', 'Dylan', 'CSE 1310', 'Henry', 'PHYS 1444', 'James', 'IE 3301', 'PHYS 1443', 'Jonathan', 'IE 3312', 'Krishna', 'CSE 1310', 'Luis', 'CSE 1310', 'Michael', 'IE 3301', 'Nang', 'PHYS 1443', 'Pramod', 'PHYS 1444', 'PHYS 1443', 'Saroj', 'IE 3301', 'MATH 1426', 'Sol', 'CSE 1310', 'Timothy', 'MATH 2325', 'IE 3301']
有什么简单的解决办法吗?
最佳答案
import itertools
print [[key, [cls[1] for cls in list(group)]]
for key, group in itertools.groupby(data, key=lambda x: x[0])]
输出
[['Adam', ['PHYS 1443']],
['Ashley', ['IE 3312', 'PHYS 1443']],
['August', ['PHYS 1444']],
['Baron', ['PHYS 1443']],
['Christopher', ['IE 3301', 'CSE 1320', 'PHYS 1443']],
['Dylan', ['CSE 1310']],
['Henry', ['PHYS 1444']],
['James', ['IE 3301', 'PHYS 1443']],
['Jonathan', ['IE 3312']],
['Krishna', ['CSE 1310']],
['Luis', ['CSE 1310']],
['Michael', ['IE 3301']],
['Nang', ['PHYS 1443']],
['Pramod', ['PHYS 1444', 'PHYS 1443']],
['Saroj', ['IE 3301', 'MATH 1426']],
['Sol', ['CSE 1310']],
['Timothy', ['MATH 2325', 'IE 3301']]]
关于python - 将一维列表转换为二维列表(写入错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672018/