Reputation: 1
I am attempting to join certain list elements in a specific manner: assuming i have following lists:
simpleline= [ 4 ]
otherline= [ 5, 7 ]
nextline=[ 1, 2 ]
i want to generate following lists:
middlelist=[ [ 4, 5 ] , [ 4, 7 ] ]
then finally:
finallist=[ [ 4, 5, 1] , [4, 7, 1] , [ 4, 5, 2 ] , [ 4, 7, 2 ] ]
i have attempted the first process in a cycle:
simpleline= [ 4 ]
otherline= [ 5, 7 ]
nextline=[ 1, 2 ]
middlelist=[]
for element in range(len(otherline)):
snap=simpleline[0].append(otherline[element])
middlelist.append(snap)
print middlelist
however this results in error:
AttributeError: 'int' object has no attribute 'append'
i appreciate any help
Upvotes: 0
Views: 44
Reputation: 4606
Can use list comprehension here, just need to concatenate for the final list
middle = [[i, j] for i in simpleline for j in otherline]
# [[4, 5], [4, 7]]
final = [j + [i] for i in nextline for j in middle]
# [[4, 5, 1], [4, 7, 1], [4, 5, 2], [4, 7, 2]]
Upvotes: 0
Reputation: 51335
I would use itertools.product
for this:
finallist = list(map(list, itertools.product(*[simpleline,otherline,nextline])))
>>> finallist
[[4, 5, 1], [4, 5, 2], [4, 7, 1], [4, 7, 2]]
If you need the middlelist
too:
middlelist = list(map(list, itertools.product(*[simpleline,otherline])))
>>> middlelist
[[4, 5], [4, 7]]
Upvotes: 1