Reputation: 11
I want to make multiple lists with my for loops, My code is:
for port in portlist1:
print port.getname(),port.getsize()
for register in port.getregisters():
j=j+1
print j
j=0
Output is:
B 10
1
C 15
1
F 30
1
I want to make list every time:
List1=[[B,10],1]
List2=[[C,15],1]
List3=[[F,30],1]
Can someone help me here?
Upvotes: 0
Views: 125
Reputation: 2200
It's a bad idea to make a new list each time, you should just go with nesting each list. If the amount of ports is static, you can use vars()['listX']
.. But still not really recomended. You should go with the answer given by kroolik
or alecxe
But if you REALLY need someting like..:
List1=[[B,10],1]
List2=[[C,15],1]
List3=[[F,30],1]
You can use:
lname = "list"
for i,p in enumerate(portlist1):
j = len(p.getregisters())
vars()[lname+str(i)] = [(p.getname(),p.getsize()), j]
print list0
print list1
print list2
Upvotes: 1
Reputation: 473763
It's not clear what was the value of j
before the loop, but it looks like you are using it to measure the length of port.getregisters()
. Try this one-liner:
result = [[[port.getname(), port.getsize()], len(port.getregisters())] for port in portlist1]
Upvotes: 2
Reputation: 15854
lists = []
for port in portlist1:
l = [[port.getname(), port.getsize()]]
for register in port.getregisters():
j=j+1
l.append(j)
lists.append(l)
j=0
Upvotes: 2