[Tutor] Unpacking lists
Alan Gauld
alan.gauld at btinternet.com
Wed Jul 9 07:58:26 CEST 2014
On 09/07/14 02:44, Robert Nanney wrote:
> #!/usr/bin/python
> #list_test2.py
>
> list1 = [1, 8, 15]
> list2 = [2, 9, 16]
> list3 = [[3, 4, 5, 6], [10, 11, 12, 13], [17, 18, 19, 20]]
> list4 = [7, 14, 21]
> one_list = zip(list1, list2, list3, list4)
> first_round = [one_list[x][y] for x in range(len(list3)) for y in range(4)]
My first thought is that you are using indexing too much.
The above would be clearer using:
first_round = [tup[x] for tup in one_list for x in range(4)]
> second_round = []
> for i in first_round:
> if not isinstance(i, list):
> second_round.append(i)
> else:
> for x in range(len(i)):
> second_round.append(i[x])
and this loop could be
for item in i:
second_round.append(item)
But I think list addition would do the job more easily.
Something like (untested)
second_round += i
> While this seems to do the trick, I feel there is probably a
> better/more pythonic way to accomplish the same thing.
I agree but I don;t have time right now to figure it out!
But it seems there should be a more straightforward method.
I'm thinking something like
result = []
for L in (list1,list2,list3):
if isinstance(L,list)
result += L
else: result.append(L)
mebbe...
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list