如何用许多变量填充列表

2024-04-20 02:44:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些变量,我需要比较每个变量,并根据比较结果填写三个列表,如果var == 11添加到lista_a,如果var == 21添加到lista_b…,如:

inx0=2 inx1=1 inx2=1 inx3=1 inx4=4 inx5=3 inx6=1 inx7=1 inx8=3 inx9=1
inx10=2 inx11=1 inx12=1 inx13=1 inx14=4 inx15=3 inx16=1 inx17=1 inx18=3 inx19=1
inx20=2 inx21=1 inx22=1 inx23=1 inx24=2 inx25=3 inx26=1 inx27=1 inx28=3 inx29=1

lista_a=[]
lista_b=[]
lista_c=[]

#this example is the comparison for the first variable inx0
#and the same for inx1, inx2, etc...
for k in range(1,30):
    if inx0==1:
        lista_a.append(1)
    elif inx0==2:
        lista_b.append(1)
    elif inx0==3:
        lista_c.append(1)

我需要得到:

#lista_a = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
#lista_b = [1,1,1]
#lista_c = [1]

Tags: the列表forvarelifappendlistainx2
1条回答
网友
1楼 · 发布于 2024-04-20 02:44:54

你的inx*变量应该是一个列表:

inx = [2,1,1,1,4,3,1,1,3,1,2,1,1,1,4,3,1,1,3,1,2,1,1,1,2,3,1,1,3,1]

然后,找出它有多少个2:

inx.count(2)

如果必须的话,您可以从中构建一个新列表:

list_a = [1]*inx.count(1)
list_b = [1]*inx.count(2)
list_c = [1]*inx.count(3)

但把这些列在一张单子上似乎很愚蠢。实际上,您需要保留的唯一数据是一个整数(计数),那么为什么还要麻烦地携带一个列表呢?你知道吗


获取列表的另一种方法是使用defaultdict:

from collections import defaultdict
d = defaultdict(list)
for item in inx:
    d[item].append(1)

在这种情况下,您想要作为list_a的内容可以通过d[1]访问,list_b可以作为d[2]访问,等等


或者,如注释中所述,您可以使用collections.Counter获得计数:

from collections import Counter #python2.7+
counts = Counter(inx)
list_a = [1]*counts[1]
list_b = [1]*counts[2]
...

相关问题 更多 >