This question already has answers here:
How to merge lists into a list of tuples?
(10 answers)
How to pair up two lists? [duplicate]
(3 answers)
Closed 4 years ago.
I have two lists and I would like to create a list of lists but mainting the order, so if I have:
l1 = [1,2,3,2]
l2 = [2,3,4,1]
I would like to have:
ans = [[1,2],[2,3],[3,4],[2,1]]
It mantains the order of the indexes
Thank you!
You can use zip,
ans = [[a, b] for a, b in zip(l1, l2)]
You can find a good tutorial about zip in this tutorial.
In case one of the lists is longer then the other, you can use zip_longest (documented here):
from iterators import zip_longest
l1 = [1,2,3,2,7]
l2 = [2,3,4,1]
ans = [[a, b] for a, b in zip_longest(l1, l2, fillvalue=0)]
# output: ans = [[1,2],[2,3],[3,4],[2,1],[7,0]]
>>> l1 = [1,2,3,2]
>>> l2 = [2,3,4,1]
>>> ans = [[1,2],[2,3],[3,4],[2,1]]
>>> [list(v) for v in zip(l1, l2)]
[[1, 2], [2, 3], [3, 4], [2, 1]]
>>> assert _ == ans
You can simply do following:
l1 = [1,2,3,2]
l2 = [2,3,4,1]
ans = zip(l1, l2) #convert to tuples
ans = map(list, ans) #convert every tuples to list
for pairs in ans:
print pairs
EDIT: izip is needed for python2 only. In Python 3 the built-in zip does the same job as itertools.izip in 2.x (returns an iterator instead of a list
Using zip
l1 = [1,2,3,2]
l2 = [2,3,4,1]
zip(l1, l2)
# [(1, 2), (2, 3), (3, 4), (2, 1)]
Note that zip return list type:
type(zip(l1, l2))
# <type 'list'>
It means zip computes all the list at once, which is not memory efficient when your l1, l2 is large. For saving memory, using izip: izip computes the elements only when requested.
from itertools import izip
y = izip(l1, l2)
for item in y:
print(item)
# (1, 2), (2, 3), (3, 4), (2, 1)
print(type(y))
# <itertools.izip object at 0x7f628f485f38>
Related
I want to write a function that takes three lists of integers, l1, l2, and l3, and returns
a list of all tuples, where each tuple (a,b,c) is such that a is from l1, b is
from l2 and c is from l3 and a+b=c.
Expected Output:
[(2,5,7), (3,4,7), (3,5,8)]
The output I got:
None
Here is the code that I have written:
def threeList(l1, l2, l3):
result = []
for num in list3:
for x in list1:
for y in list2:
if x + y == num:
tuples = (x,y,num)
list_of_tuples = result.extend(tuples)
return list_of_tuples
list1 = [1,2,3]
list2 = [4,5]
list3 = [7,8]
threeList(list1, list2, list3)
Try this:
import itertools as it
list1 = [1,2,3]
list2 = [4,5]
list3 = [7,8]
[(x,y,x+y) for x,y in it.product(list1,list2) if x+y in list3]
which returns:
> [(2, 5, 7), (3, 4, 7), (3, 5, 8)]
itertools.product is a clean replacement for nested for loops.
extend is an in-place method which returns None.
Change your code to:
def threeList(l1, l2, l3):
result = []
for num in l3:
for x in l1:
for y in l2:
if x + y == num:
tuples = (x, y, num)
result.append(tuples)
return result
list1 = [1, 2, 3]
list2 = [4, 5]
list3 = [7, 8]
print(threeList(list1, list2, list3))
Output:
[(2, 5, 7), (3, 4, 7), (3, 5, 8)]
Explanation :
I used append instead of extend because we want the tuple tuples itself not the items inside it. Also I replaced the names list3, list1, list2 with l3, l1, l2 respectively because these are the actual values passed to the function, if your code works now is because list1, list2, list3 are exist in outside and those are referenced inside the function. Then after the loop finishes I return the result which is a list of tuples.
This was to fix your solution, but a better alternative solution is to use itertools modules like product in your situation.
Extend modifies the object itself. It does not return anything.
result.extend(tuples)
return result
Also note your code snippet is not working. So it is hard to spot your exact issue.
Did you make a typo?
Indentation wrong?
etc
I have a list:
list = [1, 2, 3]
I want to get this list and add a tuple so this list becomes like this
T_list = [(1,x), (2, x), (3,x)]
How do I do it?
Use a simple list comprehension to do this:
>>> your_list = [1, 2, 3]
>>> x = 100
>>> your_list_with_tuples = [(k, x) for k in your_list]
>>> your_list_with_tuples
Output
[(1, 100), (2, 100), (3, 100)]
Also, don't name your variables list, dict, etc, because they shadow the builtin types/functions.
A list comprehension would do the trick:
t_list = [(y,x) for y in original_list]
Also, the commenter is right. Don't name your lists list. It's a built in function. Using it for something else could cause problems down the line.
Here's my attempt, although I'm not an expert.
lis = [1,2,3]
tup = (4, 5, 6)
new_tup = tuple(lis)
new_lis = []
for i in range(0,3):
data = (new_tup[i],tup[i])
new_lis.append(data)
print(new_lis)
Good Day, I've googled this question and have found similar answers but not what I am looking for. I am not sure what the problem is called so I that doesn't help me and I am looking for an elegant solution.
How do I loop over a list, item at a time, and compare it to all other items in a list. For example, if I had a list
l = [1,2,3,4]
Each loop of the out would yield something like
1 vs [2,3,4]
2 vs [1,3,4]
3 vs [1,2,4]
4 vs [1,2,3]
One solution I've been playing with involves duplicating the list every iteration, finding the index of the item, deleting it from the duplicate list and compare the two. This route seems less ideal as you have to create a new list on every iteration.
You can use itertools.combiations to create all combinations of the length 3 from your list and then use set.defference method to get the difference element between the l and the combinations. but note that you need to convert your main list to a set object :
>>> from itertools import combinations
>>> l = {1,2,3,4}
>>> [(l.difference(i).pop(),i) for i in combinations(l,3)]
[(4, (1, 2, 3)), (3, (1, 2, 4)), (2, (1, 3, 4)), (1, (2, 3, 4))]
A simple approach would be to use two loops:
arr = [1,2,3,4]
for i in arr:
comp = []
for j in arr:
if i != j:
comp.append(j)
print(comp)
I guess you could use list comprehension. While still creating a new list every iteration, you don't need to delete an item each time:
l = [1,2,3,4]
for i in l:
temp = [item for item in l if item != i]
print temp
[2, 3, 4]
[1, 3, 4]
[1, 2, 4]
[1, 2, 3]
I have a list of tuples:
l=[(1,2,3),(4,5,6)]
The list can be of arbitrary length, as can the tuples. I'd like to convert this into a list or tuple of the elements, in the order they appear:
f=[1,2,3,4,5,6] # or (1,2,3,4,5,6)
If I know the at development time how many tuples I'll get back, I could just add them:
m = l[0] + l[1] # (1,2,3,4,5,6)
But since I don't know until runtime how many tuples I'll have, I can't do that. I feel like there's a way to use map to do this, but I can't figure it out. I can iterate over the tuples and add them to an accumulator, but that would create lots of intermediate tuples that would never be used. I could also iterate over the tuples, then the elements of the tuples, and append them to a list. This seems very inefficient. Maybe there's an even easier way that I'm totally glossing over. Any thoughts?
Chain them (only creates a generator instead of reserving extra memory):
>>> from itertools import chain
>>> l = [(1,2,3),(4,5,6)]
>>> list(chain.from_iterable(l))
[1, 2, 3, 4, 5, 6]
l = [(1, 2), (3, 4), (5, 6)]
print sum(l, ()) # (1, 2, 3, 4, 5, 6)
reduce(tuple.__add__, [(1,2,3),(4,5,6)])
tuple(i for x in l for i in x) # (1, 2, 3, 4, 5, 6)
Use the pythonic generator style for all of the following:
b=[(1,2,3),(4,5,6)]
list = [ x for x in i for i in b ] #produces a list
gen = ( x for x in i for i in b ) #produces a generator
tup = tuple( x for x in i for i in b ) #produces a tuple
print list
>> [1, 2, 3, 4, 5, 6]
>>> from itertools import chain
>>> l = [(1,2,3),(4,5,6)]
>>> list(chain(*l))
[1, 2, 3, 4, 5, 6]
You can combine the values in a list using the .extend() function like this:
l = [(1,2,3), (4,5,6)]
m = []
for t in l:
m.extend(t)
or a shorter version using reduce:
l = [(1,2,3), (4,5,6)]
m = reduce(lambda x,y: x+list(y), l, [])
This question already has answers here:
Sorting list based on values from another list
(20 answers)
Closed 8 years ago.
I have the two lists in Python
list_1 = [5, 2, 8];
list_2 = ['string1', 'string2', 'string3']
I would like to sort the fist list and use the result to sort the second list.
In other words, the result should be:
# Sorted in descending order
list_1_sorted = [8, 5, 2];
list_2_sorted = ['string3', 'string1', 'string2'];
I know how to sort each of these lists individually, but how I can permute one list using the permutation of indices resulting from sorting the other list?
Schwartzian transform
list_1_sorted, list_2_sorted = zip(*sorted(zip(list_1, list_2),
key=operator.itemgetter(0), reverse=True))
Zip the lists together, sort, unzip the lists:
together = zip(list_1, list_2)
sorted_together = sorted(together)
list_1_sorted = [x[0] for x in sorted_together]
list_2_sorted = [x[1] for x in sorted_together]
What's happening here is that zip creates a list of tuples, with the elements you want the list to be sorted by being the first elements:
>>> a = [1,3,7,3,2]
>>> b = ["one","two",'three','four','five']
>>> zip(a,b)
[(1, 'one'), (3, 'two'), (7, 'three'), (3, 'four'), (2, 'five')]
Then when you sort them, they elements stay paired:
>>> sorted(zip(a,b))
[(1, 'one'), (2, 'five'), (3, 'four'), (3, 'two'), (7, 'three')]
Then all that's left is to unpack these lists.
You can use zip:
>>> list_1 = ['string1', 'string2', 'string3']
>>> list_2 = [5, 2, 8]
>>> s = sorted(zip(list_2, list_1), reverse=True)
>>> list_1_sorted = [e[1] for e in s]
>>> list_2_sorted = [e[0] for e in s]
>>> list_1_sorted
['string3', 'string1', 'string2']
>>> list_2_sorted
[8, 5, 2]
>>>
#Ignacio's answer is the best, but just in case you need to sort the lists in-place without making new lists, you can try this:
import itertools
list_enumerate = itertools.count()
list_2.sort(reverse=True, key=lambda k: list_1[next(list_enumerate)])
list_1.sort(reverse=True)
print list_1
print list_2
Note that I do not think there is any guarantee that the key function is called for each list item in order (which is necessary for this to work), so this is a risky method to use.