如何将不同的元素添加到列表中的列表? Python 3

时间:2012-10-09 12:43:25

标签: python arrays list append

f = open("sonad.txt",encoding="utf-8")
c = f.readlines()
blokk = [[]] * 15
for read in c:
    length = len(read.strip())
    blokk[length].append(read.strip())

sonad.txt只有一些随机的单词,我想把它们放在这样的顺序中:

所有单词,长达1个字母的单词去blokk [1]                         2个字母长到blokk [2] 等等...

但是我当前的代码所做的是它为allL block [x]添加了一个元素 blokk [1] blokk [2] blokk [3] .....都是一样的。

2 个答案:

答案 0 :(得分:7)

blokk = [[]] * 15行创建了一个列表,其中包含相同的空列表 15次。

您想要使用列表理解:

blokk = [[] for _ in range(15)]

亲自试试:

>>> blokk = [[]]*15
>>> blokk
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>> blokk[0].append(1)
>>> blokk
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
>>> blokk = [[] for _ in range(15)]
>>> blokk
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>> blokk[0].append(1)
>>> blokk
[[1], [], [], [], [], [], [], [], [], [], [], [], [], [], []]

答案 1 :(得分:4)

 blokk = [[]]*15

创建了对相同列表的15个引用。因此,如果您追加到blokk[0]block[1],则这些更改将反映在任一列表中,因为它们属于同一列表。

这里可能更好的数据结构是defaultdict

from collections import defaultdict
d = defaultdict(list)
with open('sonad.txt', encoding='utf-8') as fin:
    for line in fin:
        stripped = line.strip()
        d[len(stripped)].append(stripped)

print(sorted(d.items()))