How do you append each item of one list to each sublist of another list?
a = [['a','b','c'],['d','e','f'],['g','h','i']]
b = [1,2,3]
Result should be:
[['a','b','c',1],['d','e','f',2],['g','h','i',3]]
Keep in mind that I want to do this to a very large list, so efficiency and speed is important.
I've tried:
for sublist,value in a,b:
sublist.append(value)
it returns 'ValueError: too many values to unpack'
Perhaps a listindex or a listiterator could work, but not sure how to apply here
a = [['a','b','c'],['d','e','f'],['g','h','i']]
b = [1,2,3]
for ele_a, ele_b in zip(a, b):
ele_a.append(ele_b)
Result:
>>> a
[['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]
The reason your original solution did not work, is that a,b does create a tuple, but not what you want.
>>> z = a,b
>>> type(z)
<type 'tuple'>
>>> z
([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']], [1, 2, 3])
>>> len(z[0])
3
>>> for ele in z:
... print ele
...
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] #In your original code, you are
[1, 2, 3] #unpacking a list of 3 elements
#into two values, hence the
#'ValueError: too many values to unpack'
>>> zip(a,b) # using zip gives you what you want.
[(['a', 'b', 'c'], 1), (['d', 'e', 'f'], 2), (['g', 'h', 'i'], 3)]
Here is a simple solution:
a = [['a','b','c'],['d','e','f'],['g','h','i']]
b = [1,2,3]
for i in range(len(a)):
a[i].append(b[i])
print(a)
One option, using list comprehension:
a = [(a[i] + b[i]) for i in range(len(a))]
Just loop through the sublists, adding one item at a time:
for i in range(0,len(listA)):
listA.append(listB[i])
You can do:
>>> a = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> b = [1,2,3]
>>> [l1+[l2] for l1, l2 in zip(a,b)]
[['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]
You can also abuse a side effect of list comprehensions to get this done in place:
>>> [l1.append(l2) for l1, l2 in zip(a,b)]
[None, None, None]
>>> a
[['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]
Related
I have a list like this:
my_list = [['a', 'b', 'c', 'd'], ['a', 'e', 'f', 'd'], ['a', 'b', 'c', 'g'], ['d', 'e', 'f', 'd']]
and I want to compare its items with another list:
main_list = ["a", "b", "f", "d"]
And I want to return the indexes that they differ. My code so far looks like this:
differences = []
my_list = [['a', 'b', 'c', 'd'], ['a', 'e', 'f', 'd'], ['a', 'b', 'c', 'g'], ['d', 'e', 'f', 'd']]
main_list = ["a", "b", "f", "d"]
for i in range(len(my_list)):
for index, (first, second) in enumerate(zip(my_list[i], main_list), start=1):
if first != second:
differences.append(index)
print(differences)
With the above code I get this output:
[3, 2, 3, 4, 1, 2]
Which is exactly the indices the main list differs with the original list. However I would like to get this list as an output, which gives me a nested list of which each index is the indices the main list differs with my_list[0], then with my_list[1] and so on:
[[3], [2], [3, 4], [1, 2]]
I would appreciate some help on modifying the code to get the ideal output.
Thanks!
my_list = [['a', 'b', 'c', 'd'], ['a', 'e', 'f', 'd'], ['a', 'b', 'c', 'g'], ['d', 'e', 'f', 'd']]
main_list = ["a", "b", "f", "d"]
out = []
for subl in my_list:
out.append([i for i, (a, b) in enumerate(zip(subl, main_list), 1) if a != b])
print(out)
Prints:
[[3], [2], [3, 4], [1, 2]]
Or one liner:
out = [[i for i, (a, b) in enumerate(zip(subl, main_list), 1) if a != b] for subl in my_list]
print(out)
How one might get Sympy Permutation to act on a list? E.g.,
from sympy.combinatorics import Permutation
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
perm = Permutation([[0, 2, 8, 6], [1, 5, 7, 3]])
# Then something like...
perm * lst # This doesn't work. Throws AttributeError because of list
I'd like something like this that returns (in this example):
['g', 'd', 'a', 'h', 'e', 'b', 'i', 'f', 'c']
I have read https://docs.sympy.org/latest/modules/combinatorics/permutations.html, and don't see how.
Any suggestions as to how might one go about this?
You can just do perm(lst)
>>> from sympy.combinatorics import Permutation
>>> lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> perm = Permutation([[0, 2, 8, 6], [1, 5, 7, 3]])
>>> perm(lst)
['c', 'f', 'i', 'b', 'e', 'h', 'a', 'd', 'g']
Your example output seems to have the result of applying the reverse of the given Permutation to the list - if that is your required output you need to either reverse the final list or each list within the permutation.
From here:
The permutation can be ‘applied’ to any list-like object, not only Permutations.
In python, if I have the list of elements
l = ['a', 'b', 'c', 'd', 'e', 'f']
and a list of numbers
n = [2, 1, 3]
How I can split the list l by the numbers in n ?
And get this list of lists
[['a', 'b'], ['c'], ['d', 'e', 'f']]
You could use islice:
>>> from itertools import islice
>>> l = ['a', 'b', 'c', 'd', 'e', 'f']
>>> n = [2, 1, 3]
>>> it = iter(l)
>>> out = [list(islice(it, size)) for size in n]
>>> out
[['a', 'b'], ['c'], ['d', 'e', 'f']]
It's a bit obfuscated, but still:
ll = [[l.pop(0) for _ in range(k)] for k in n]
Note that this traversal will not leave the list intact because of the pop() thingy.
You can create an iterator out of the list. Then call next the appropriate number of times.
>>> l = ['a', 'b', 'c', 'd', 'e', 'f']
>>> n = [2, 1, 3]
>>> it = iter(l)
>>> [[next(it) for i in xrange(k)] for k in n]
[['a', 'b'], ['c'], ['d', 'e', 'f']]
Yet another way
if __name__ == '__main__':
l = ['a', 'b', 'c', 'd', 'e', 'f']
n = [2, 1, 3]
result = []
for i in n:
j = l[:i]
result.append(j)
l = l[i:]
print result
Gives
[['a', 'b'], ['c'], ['d', 'e', 'f']]
It's not as short as some other solutions, but it sure as hell is readable
cuts = [sum(n[:i]) for i in range(len(n) + 1)]
>>> [l[cuts[i]:cuts[i + 1]] for i in range(len(cuts) - 1)]
[['a', 'b'], ['c'], ['d', 'e', 'f']]
This leaves the list intact:
>>> l
['a', 'b', 'c', 'd', 'e', 'f']
I think this would be most optimized as it will only required len(n) number of iterations.
l = ['a', 'b', 'c', 'd', 'e', 'f']
n = [2, 1, 3]
res = []
temp = 0
for i in n:
res.append(l[temp:temp+i])
temp = temp+i
print res
Returns:
[['a', 'b'], ['c'], ['d', 'e', 'f']]
You can use numpy.split :
>>> np.split(l,[sum(n[:i]) for i in range(len(n))])
[array([], dtype=float64), array(['a', 'b'],
dtype='|S1'), array(['c'],
dtype='|S1'), array(['d', 'e', 'f'],
dtype='|S1')]
I currently have this function, which I'd like to make scalable to take in more lists. In other words, I'd like to use this function whether I have to combine 2 lists or 10 lists.
l1 = [['a','b','c'],['d','e','f']]
l2 = [['A','B','C'],['D','E','F']]
[L1 + L2 for L1, L2 in zip(l1, l2)]
result should be:
[['a','b','c','A','B','C'],['d','e','f','D','E','F']]
Use:
[sum(l, []) for l in zip(*lists)]
Demo:
>>> l1 = [['a', 'b', 'c'], ['d', 'e', 'f']]
>>> l2 = [['A', 'B', 'C'], ['D', 'E', 'F']]
>>> lists = (l1, l2)
>>> [sum(l, []) for l in zip(*lists)]
[['a', 'b', 'c', 'A', 'B', 'C'], ['d', 'e', 'f', 'D', 'E', 'F']]
or, as a function:
def combine_lists(*lists):
return [sum(l, []) for l in zip(*lists)]
combine_lists(l1, l2)
Let's say I had a list:
[a, b, c, d, e, f]
Given an index, say 3, what is a pythonic way to remove everything before
that index from the front of the list, and then add it to the back.
So if I was given index 3, I would want to reorder the list as
[d, e, f, a, b, c]
>>> l = ['a', 'b', 'c', 'd', 'e', 'f']
>>>
>>> l[3:] + l[:3]
['d', 'e', 'f', 'a', 'b', 'c']
>>>
or bring it into a function:
>>> def swap_at_index(l, i):
... return l[i:] + l[:i]
...
>>> the_list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> swap_at_index(the_list, 3)
['d', 'e', 'f', 'a', 'b', 'c']
use the slice operation
e.g.,
myList = ['a', 'b','c', 'd', 'e', 'f']
myList[3:] + myList[:3]
gives
['d', 'e', 'f', 'a', 'b', 'c']
def foo(myList, x):
return myList[x:] + myList[:x]
Should do the trick.
Call it like this:
>>> aList = ['a', 'b' ,'c', 'd', 'e', 'f']
>>> print foo(aList, 3)
['d', 'e', 'f', 'a', 'b', 'c']
EDIT Haha all answers are the same...
The pythonic way it's that's sdolan said, i can only add the inline way:
>>> f = lambda l, q: l[q:] + l[:q]
so, you can use like:
>>> f([1,2,3,4,5,6], 3)
[4, 5, 6, 1, 2, 3]