Reputation: 86
I have a list of lists mainList
. I wish to append this list with a subList
, but only the 2nd, 3rd, 4th, 5th, and 7th items.
for subList in file:
mainList.append(subList[#items 2,3,4,5,7])
Is there a way to do this besides
for subList in file:
temp = []
for item in subList[1:]:
if #item not the 6th item:
temp.append(item)
mainList.append(temp)
Can I do this without the temp
list and the nested for loop appending this list?
Upvotes: 2
Views: 69
Reputation: 362478
I would do it like this, simple and Pythonic with a list comprehension:
indices = 2,3,4,5,7
mainList.append([sublist[i] for i in indices])
Upvotes: 5
Reputation: 12927
This should do:
mainList.extend(subList[1:6])
mainList.append(subList[7])
Upvotes: 0
Reputation: 78536
You can use operator.itemegetter
to fetch the items from subList
, returning a tuple. You can afterwards cast to a list before appending:
from operator import itemgetter
f = itemgetter(2,3,4,5,7)
for subList in file:
mainList.append(list(f(subList)))
You may drop the list call if your sublist could also pass as tuples.
Upvotes: 3