简体   繁体   中英

how I fill a list with many variables python

I have a some variables and I need to compare each of them and fill three lists according the comparison, if the var == 1 add a 1 to lista_a , if var == 2 add a 1 to lista_b ..., like:

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)

I need get:

#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]

Your inx* variables should almost certinaly be a list to begin with:

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]

Then, to find out how many 2's it has:

inx.count(2)

If you must, you can build a new list out of that:

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

but it seems silly to keep a list of ones. Really the only data you need to keep is a single integer (the count), so why bother carrying around a list?


An alternate approach to get the lists of ones would be to use a defaultdict:

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

in this case, what you want as list_a could be accessed by d[1] , list_b could be accessed as d[2] , etc.


Or, as stated in the comments, you could get the counts using a collections.Counter :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM