0

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?

2
  • So essentially you want your output formatted differently? Commented Jul 17, 2013 at 18:30
  • 1
    Use list comprehensions: [ [[p.getname(),p.getsize()],len(p.getregisters())] for p in portlist1] Commented Jul 17, 2013 at 18:34

3 Answers 3

2
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
Sign up to request clarification or add additional context in comments.

1 Comment

Inline as suggested by alecxe or using generator makes code much, much faster than your variant with multiple lookup overheads like l.append. BTW, j=j+1 = lol. --> j+=1
2

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]

2 Comments

missing close paren on len() call
@alecxe Да пожалуйста! ;)
1

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

7 Comments

vars()[lname+str(i)] is unpythonic
@akaRem : It's not like I recommended it, I just answered his question: «Creating multiple list from loops»
It really looks like you recommend it for solving this problem.. Uh.
@akaRem, read it again: "But still not really recomended. You should go with the answer given by kroolik or alecxe". I answered the question, where he ASKED to have diffrent lists as output "I want to make list every time:*example given*".
"I want to make list every time" -> Use yield which is fast and memory-safe.. But I'll stop pushing. ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.