2

Changing the Two-Dimensional One-Dimensional List 1

 2 years ago
source link: https://www.codesd.com/item/changing-the-two-dimensional-one-dimensional-list-1.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Changing the Two-Dimensional One-Dimensional List 1

advertisements

Possible Duplicate:
Flattening a shallow list in Python

I want to create a function that takes a 2 dimensional list and outputs a 1 dimensional list with the same contents. Here is what I have:

twoDlist= [[23, 34, 67],[44,5,3],[7,8,9]]

def twoone (list1):

for x in range (len(list1)):
    for y in range(len(list1)):
        list2=[]
        list2.append(list1[x][y])

print twoone(twoDlist)

Only problem it returns 'None'. What am I doing wrong here? Can someone suggest a better idea?


Two issues here, the first is that you are not returning a value and the second is that you are resetting list2 to an empty list inside of your nested loop, so at the end you would only have a single element in it.

Here is how you could fix your code:

def twoone(list1):
    list2 = []
    for x in range(len(list1)):
        for y in range(len(list1)):
            list2.append(list1[x][y])
    return list2

>>> twoone(twoDlist)
[23, 34, 67, 44, 5, 3, 7, 8, 9]

However, there are much better ways to do this, see the link in jtbandes' comment.

The best way is itertools.chain():

>>> from itertools import chain
>>> list(chain.from_iterable(twoDlist))
[23, 34, 67, 44, 5, 3, 7, 8, 9]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK