PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] how to access and collect elements from a list in list?

 July 21, 2022     append, indexing, list, loops, python     No comments   

Issue

This question is so simple, but the desired output is not clicking to me.

alist = [[0., 0., 0], [1 , 2, 3 ], [4, 5, 6 ],[7, 8, 9], [10, 11, 12], [13, 14, 15]]

a = []
for i in alist:
    for j in i:
        a.append(j[0:3])
print(a)

desired output :

a = [ [0, 1, 4, 7, 10, 13 ], [0, 2, 5, 8, 11, 14 ], [0, 3, 6, 9, 12, 15 ] ]

Solution

You can use zip like zip(*alist) and get what you want, but if you want correct your code. you need enumerate.

>>> list(map(list, zip(*alist)))
[[0.0, 1, 4, 7, 10, 13], [0.0, 2, 5, 8, 11, 14], [0, 3, 6, 9, 12, 15]]

Your code:

a = [[],[],[]]                    # <- change this
for i in alist:
    for idx, j in enumerate(i):   # <- change this
        a[idx].append(j)          # <- change this
print(a)

Output:

[[0.0, 1, 4, 7, 10, 13], [0.0, 2, 5, 8, 11, 14], [0, 3, 6, 9, 12, 15]]


Answered By - I'mahdi
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing