I've got a list of integers l = [1,2,3,4,5,6] and I want to print them in a formatted way as such:
[1,2] [3,4] [5,6]
How can I get this result in an easy way? I've tried using:
print("[%d, %d] [%d, %d] [%d, %d]" % l)
But it didn't work since l is not a number. Any pointers on how this effect can be achieved would be appreciated.
I know I can use
print("[", l[0], "," ,1[1] ...
But that is way to ugly and ineffective to write code, and was hoping for a better way.
If the number of elements is fixed, we can try this:
lst = [1, 2, 3, 4, 5, 6]
print('[{}, {}] [{}, {}] [{}, {}]'.format(*lst))
=> '[1, 2] [3, 4] [5, 6]'
You can group the list items in pairs by creating an iterator from the list and zipping the iterator with itself:
i = iter(l)
print(*map(list, zip(i, i)))
This outputs:
[1, 2] [3, 4] [5, 6]
l = [1,2,3,4,5,6]
print(*map(list, zip(l[::2], l[1::2])))
Prints:
[1, 2] [3, 4] [5, 6]
How about this?
l = [1,2,3,4,5,6]
evens = [i for i in l if i % 2 == 0]
odds = [i for i in l if i % 2 != 0]
zip(evens, odds)
or this
l = [1,2,3,4,5,6,7,8]
print( *[ (l[2*i], l[2*i+1] ) for i in range(0,len(l)//2)])
produces
[1, 2] [3, 4] [5, 6]
Related
#Write a function named add_one_to_all that takes in a list of numbers and adds one to each of the original numbers
assert add_one_to_all([0, 0, 0]) == [1, 1, 1]
assert add_one_to_all([1, 2, 3]) == [2, 3, 4]
assert add_one_to_all([6, 7, 8]) == [7, 8, 9]
I've tried this
def my_list ([x,y,z]):
new_list = [x+1 for x in my_list]
def add_one_to_all(my_list):
return [x+1 for x in my_list]
def add_one_to_all(integer):
return integer+1
int_list = [1, 2, 3, 4, 5]
# Adding one on each integer
# using list comprehension.
output_list = [add_one_to_all(i) for i in int_list]
print(output_list)
The output will be [2,3,4,5,6]
You can use map
l = [1, 2, 3]
print(list(map(lambda x:x+1, l)))
result
[2, 3, 4]
I want to swap every occurrence of two elements in a list of lists. I have seen previous answers but they are different from what I'm trying to do. Also, I am looking for a clean and concise way (preferably list-comprehension) for this purpose.
Input
my_list = [[1,2], [1,3], [1,4], [3,2]]
Output
my_list = [[2,1], [2,3], [2,4], [3,1]]
I am trying to do something like this but no success:
[1 if i==2 else i, 2 if i==1 else i for i in my_list]
Here's a simple solution using list comprehension:
my_list = [[1,2], [1,3], [1,4], [3,2]]
a = 1
b = 2
my_list = [[a if i==b else b if i==a else i for i in j] for j in my_list]
print(my_list) # [[2, 1], [2, 3], [2, 4], [3, 1]]
If you want to add more elements to replace you can use a dictionary:
swap = {
1: 2,
2: 1
}
my_list = [[swap.get(i, i) for i in j] for j in my_list]
Someone else will probably answer with something better, but this would work.
def check(num):
if num == 1:
return 2
elif num == 2:
return 1
else:
return num
out = [[check(j) for j in i] for i in my_list]
If you need to swap 1's with 2's, this one-liner will work:
>>> my_list = [[1,2], [1,3], [1,4], [3,2]]
>>> print([[(lambda k: (1 if val == 2 else 2) if val in [1, 2] else val)(val) for val in sub_list] for sub_list in my_list])
[[2, 1], [2, 3], [2, 4], [3, 1]]
read the second line from right to left... in chunks!
I was curios about the question: Eliminate consecutive duplicates of list elements, and how it should be implemented in Python.
What I came up with is this:
list = [1,1,1,1,1,1,2,3,4,4,5,1,2]
i = 0
while i < len(list)-1:
if list[i] == list[i+1]:
del list[i]
else:
i = i+1
Output:
[1, 2, 3, 4, 5, 1, 2]
Which I guess is ok.
So I got curious, and wanted to see if I could delete the elements that had consecutive duplicates and get this output:
[2, 3, 5, 1, 2]
For that I did this:
list = [1,1,1,1,1,1,2,3,4,4,5,1,2]
i = 0
dupe = False
while i < len(list)-1:
if list[i] == list[i+1]:
del list[i]
dupe = True
elif dupe:
del list[i]
dupe = False
else:
i += 1
But it seems sort of clumsy and not pythonic, do you have any smarter / more elegant / more efficient way to implement this?
>>> L = [1,1,1,1,1,1,2,3,4,4,5,1,2]
>>> from itertools import groupby
>>> [key for key, _group in groupby(L)]
[1, 2, 3, 4, 5, 1, 2]
For the second part
>>> [k for k, g in groupby(L) if len(list(g)) < 2]
[2, 3, 5, 1, 2]
If you don't want to create the temporary list just to take the length, you can use sum over a generator expression
>>> [k for k, g in groupby(L) if sum(1 for i in g) < 2]
[2, 3, 5, 1, 2]
Oneliner in pure Python
[v for i, v in enumerate(your_list) if i == 0 or v != your_list[i-1]]
If you use Python 3.8+, you can use assignment expression :=:
list1 = [1, 2, 3, 3, 4, 3, 5, 5]
prev = object()
list1 = [prev:=v for v in list1 if prev!=v]
print(list1)
Prints:
[1, 2, 3, 4, 3, 5]
A "lazy" approach would be to use itertools.groupby.
import itertools
list1 = [1, 2, 3, 3, 4, 3, 5, 5]
list1 = [g for g, _ in itertools.groupby(list1)]
print(list1)
outputs
[1, 2, 3, 4, 3, 5]
You can do this by using zip_longest() + list comprehension.
from itertools import zip_longest
list1 = [1, 2, 3, 3, 4, 3, 5, 5].
# using zip_longest()+ list comprehension
res = [i for i, j in zip_longest(list1, list1[1:])
if i != j]
print ("List after removing consecutive duplicates : " + str(res))
Here is a solution without dependence on outside packages:
list = [1,1,1,1,1,1,2,3,4,4,5,1,2]
L = list + [999] # append a unique dummy element to properly handle -1 index
[l for i, l in enumerate(L) if l != L[i - 1]][:-1] # drop the dummy element
Then I noted that Ulf Aslak's similar solution is cleaner :)
To Eliminate consecutive duplicates of list elements; as an alternative, you may use itertools.zip_longest() with list comprehension as:
>>> from itertools import zip_longest
>>> my_list = [1,1,1,1,1,1,2,3,4,4,5,1,2]
>>> [i for i, j in zip_longest(my_list, my_list[1:]) if i!=j]
[1, 2, 3, 4, 5, 1, 2]
Plenty of better/more pythonic answers above, however one could also accomplish this task using list.pop():
my_list = [1, 2, 3, 3, 4, 3, 5, 5]
for x in my_list[:-1]:
next_index = my_list.index(x) + 1
if my_list[next_index] == x:
my_list.pop(next_index)
outputs
[1, 2, 3, 4, 3, 5]
Another possible one-liner, using functools.reduce (excluding the import) - with the downside that string and list require slightly different implementations:
>>> from functools import reduce
>>> reduce(lambda a, b: a if a[-1:] == [b] else a + [b], [1,1,2,3,4,4,5,1,2], [])
[1, 2, 3, 4, 5, 1, 2]
>>> reduce(lambda a, b: a if a[-1:] == b else a+b, 'aa bbb cc')
'a b c'
How to get all partitions of a set?
For example, I have array [1, 2, 3]. I need to get [[1], [2], [3]], [[1], [2, 3]], [[2], [1,3]], [[3], [1, 2]], [[1, 2, 3]].
Now, I wrote this code:
def neclusters(S, K):
for splits in itertools.combinations(range(len(S)), K):
yield np.split(S, 1 + np.array(splits))
But that code don't return [[2],[1,3]].
I could take all permutations of the original set and run this code on them. But can this be made easier?
I wrote this one for fun:
def partition(a_list):
yield [[x] for x in a_list]
for i in range(1, len(a_list) + 1):
_l = a_list[:]
yield [_l.pop(i-1), _l]
yield a_list
my_list = [1, 2, 3]
print list(partition(my_list))
#or
for p in partition(my_list):
print p
a = [1, 2, 3]
b = list()
for l in range(len(a)+1): b.append([c for c in combinations(a, l)])
print(b)
check this
Is there a function in Python to get the difference between two or more values in a list? So, in those two lists:
list1 = [1, 5, 3, 7]
list2 = [4, 2, 6, 4]
I need to calculate the difference between every value in list1 and list2.
for i in list1:
for ii in list2:
print i -ii
This gives negative values, but I want the subtraction between the values of the two lists only from highest value to lowest value for not getting negative values.
For the above lists, I expect the output to be [3, 3, 3, 3].
Thanks.
Assuming you expect [3, 3, 3, 3] as the answer in your question, you can use abs and zip:
[abs(i-j) for i,j in zip(list1, list2)]
Either zip the lists, or use numpy:
>>> list1 = [1, 5, 3, 7]
>>> list2 = [4, 2, 6, 4]
>>> [a-b for a,b in zip(list1, list2)]
[-3, 3, -3, 3]
>>> import numpy as np
>>> np.array(list1) - np.array(list2)
array([-3, 3, -3, 3])
Remember to cast the array back to a list as needed.
edit:
In response to the new requirement that the absolute values are needed: you can add abs in the list comprehension:
>>> [abs(a-b) for a,b in zip(list1, list2)]
[3, 3, 3, 3]
and the numpy solution would change to:
>>> map(abs, np.array(list1) - np.array(list2))
[3, 3, 3, 3]
You may also do if else condition inside list comprehension.
>>> [i-j if i>j else j-i for i,j in zip(list1, list2)]
[3, 3, 3, 3]
You can use zip method in order combine these two lists. See the tutorials for zip method https://docs.python.org/2/library/functions.html#zip
>>> list1 = [1, 5, 3, 7]
>>> list2 = [4, 2, 6, 4]
>>> [abs(x-y) for x, y in zip(list1, list2)]
[3, 3, 3, 3]
Avinash Raj's answer is correct, or alternatively, using map():
from operator import sub
C = map(sub, A, B)