Python list to list of tuples / list %2 [duplicate] - python

This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 3 years ago.
how can a list:
['tuple1_1', 'tuple1_2', 'tuple2_1', 'tuple2_2']
elegantly be transformed to a list of tuples:
[('tuple1_1', 'tuple1_2'), ('tuple2_1', 'tuple2_2')]
in python?
Something like %2 to form tuples maybe?

You can use the step portion of the slice syntax to step over every other element, and zip together the two slices, each starting at the 0th and 1st element respectively:
x = ['tuple1_1', 'tuple1_2', 'tuple2_1', 'tuple2_2']
list(zip(x[::2], x[1::2]))
# returns:
[('tuple1_1', 'tuple1_2'), ('tuple2_1', 'tuple2_2')]

I think you should group the elements in your list in groups of two, and convert that group into a tuple as follows:
>>> l = ['tuple1_1', 'tuple1_2', 'tuple2_1', 'tuple2_2']
>>> N = 2
>>> subList = [tuple(l[n:n+N]) for n in range(0, len(l), N)]
>>> sublist
[('tuple1_1', 'tuple1_2'), ('tuple2_1', 'tuple2_2')]

lis = [1,2,3,4]
list(zip(*([iter(lis)]*2)))
This returns
[(1,2), (3,4)]
The list can be composed of any other data types.
For grouping some other list into tuples of length n,
just replace 2 with n.

Related

How to make an array out of the nth element of items in a 2d array? [duplicate]

This question already has answers here:
How to extract the n-th elements from a list of tuples
(8 answers)
Get the nth element from the inner list of a list of lists in Python [duplicate]
(1 answer)
How to access the nth element of every list inside another list?
(3 answers)
Closed 1 year ago.
Not sure how to google this for the same reason I am not sure how to write the title.
basically if I have the array:
[[1,2,3],[4,5,6],[7,8,9]]
I want to pull say the 2nd(nth) item of each array and turn them into an array as such:
[2,5,8]
What is the quickest (preferably immediate) way to parse the array this way without using for-loops?
You can use list comprehension
x = [[1,2,3],[4,5,6],[7,8,9]]
y = [ele[1] for ele in x]
If you really don't want see loop or for, you can use map and lambda
x = [[1,2,3],[4,5,6],[7,8,9]]
y = list(map(lambda x:x[1],x))
If you don't consider a list comprehension a loop (even though it is certainly looping under the hood), you could accomplish this like:
list1 = [[1,2,3], [4,5,6], [7,8,9]]
list2 = [ e[1] for e in list1 ]

Keep in array of words just given words from another array [duplicate]

This question already has answers here:
Remove all the elements that occur in one list from another
(13 answers)
how to keep elements of a list based on another list [duplicate]
(3 answers)
Closed 3 years ago.
Given an array:
arr = ['a','b','c','d','a','b','d','f']
I would like to preprocess it with some kind of dictionary:
dictionary = ['a','b','c']
so after: arr.preprocess(dictionary) all items not exisiting in dictionary will be deleted, arr will be now like:
['a','b','c','a','b']
Here is a possible solution:
arr = ['a','b','c','d','a','b','d','f']
dictionary = ['a','b','c']
arr = [x for x in arr if x in dictionary]
[item for item in arr if item in dictionary]
Verified Solution:
arr = ['a','b','c','d','a','b','d','f']
dictionary = ['a','b','c']
li = []
li = [element for element in arr if element in dictionary]
print(li)
Cheers

size of a whole list containing tuple [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 6 years ago.
I have a list made of tuple
liste_groupe=((image1, image2, image6),(image5, image4, image8, image7, image3, image9))
and i would like to have the number of element of all the tuple ie here the result would be 9
I have tried len(liste_groupe) but it gives me 2.
So what code should I write in order to have the number of all the element of all the tuples in a list ?
There is no need to flatten the list in order to find the total length, and there is no need to use recursion if you already know the list is a simple 2D structure. This is all you need:
sum(map(len, liste_groupe))
Flatten a tuple of tuples into a list,
>>> liste_groupe=(('image1', 'image2', 'image6'),('image5', 'image4', 'image8', 'image7', 'image3', 'image9'))
>>> l = [item for t in liste_groupe for item in t]
>>> len(l)
9
# Or use itertools.chain
>>> import itertools
>>> l = list(itertools.chain(*liste_groupe))
>>> len(l)
9
If you only care about the number of elements,
>>> count = sum([len(t) for t in liste_groupe])
>>> count
9
You can follow a recursive approach:
def tuple_length( t ):
if type(t) != tuple:
return 1
length = 0
for element in t:
length += tuple_length( element )
return length
Now, tuple_length(liste_groupe) will return 9 as expected.
Recursion could accomplish this for you. With the following function the size of an n-dimensional tuple or list could be counted.
def calculate_size(data_set, size=0):
for i in data_set:
if isinstance(i, tuple) or isinstance(i, list):
size += calculate_size(i)
else:
size += 1
return size
Will work for a single nested list. For deeper or irregularly nested lists, you'll need a recursive function that uses chain.
from itertools import chain
cnt = len(list(chain.from_iterable(list_group)))

How to convert a python list containing several lists into single list? [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 6 years ago.
How do I convert a list of lists to a single list?
Input:
a=[['AA'], ['AE'], ['AH'], ['AO'],]
Desired output:
['AA','AE','AH','AO']
a=[['AA'], ['AE'], ['AH'], ['AO'],]
l=[]
for i in a:
l.extend(i)
print l
you could use comprehension list:
or using map and lambda functions
a=[['AA'], ['AE'], ['AH'], ['AO'],]
# open the item [0] with generators
Newa = [x[0] for x in a]
>>>['AA', 'AE', 'AH', 'AO']
see examples: http://www.secnetix.de/olli/Python/list_comprehensions.hawk
EDIT:
for i, value in enumerate(a):
a[i] = value[0]

How to remove duplicate lists in a list of list? [duplicate]

This question already has answers here:
Removing duplicates from a list of lists
(16 answers)
Closed 4 years ago.
I want to remove all duplicates list from a list of list.
So I have a list of lists like this.
a = [[1,2],[1,2],[3,4,5],[3,4,5],[3,4,5]]
I want to have:
b = [[1,2],[3,4,5]]
I don't know how to do it.
You could use a set:
b_set = set(map(tuple,a)) #need to convert the inner lists to tuples so they are hashable
b = map(list,b_set) #Now convert tuples back into lists (maybe unnecessary?)
Or, if you prefer list comprehensions/generators:
b_set = set(tuple(x) for x in a)
b = [ list(x) for x in b_set ]
Finally, if order is important, you can always sort b:
b.sort(key = lambda x: a.index(x) )
See mgilson's answer if the order of the lists is not important. If you want to retain the order, do something like:
b = list()
for sublist in a:
if sublist not in b:
b.append(sublist)
This will keep the order in the original list. However, it is slower and more verbose than using sets.

Categories

Resources