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)))
Related
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.
This question already has answers here:
Why does len() not support iterators?
(2 answers)
Closed 7 months ago.
Getting the length of reversed list doesn't work:
lst = [1,2,3]
lst = reversed(lst)
print len(lst)
throws TypeError: object of type 'listreverseiterator' has no len()
A work around is:
lst = [1,2,3]
lst_length = len(lst)
lst = reversed(lst)
print lst_length
# OR
lst = lst[::-1]
print len(lst)
Now my real question is why?
Simply reversing a list does not alter the length of the list,
so why is Python throwing that exception?
The function reversed() returns an iterator, not an actual list.
You cannot directly get the len() of an iterator (see here).
You could instead reverse the list using Extended Slice syntax:
lst_reversed = lst[::-1]
or reverse the list in place:
lst.reverse()
If you must use an iterator you could first turn it into a list:
lst_reversed = list(reversed(lst))
With each of these approaches len() will then work as expected.
reversed doesn't produce new list, it just return iterator object. You can use lst.reverse() - and it doesn't return anything, but make your lst in reversed order
reversed returns iterator so to determine length you have to consume it.
For example rev_len = len(list(reversed(lst))).
FYI list.reverse method reverses a list in place: lst.reverse()
Anyway your reversed list has the same size as the original one, so you can just determine the length even before reversing.
How do you find the length of a multi-dimensional list?
I've come up with a way myself, but is this the only way to find the number of values in a multi-dimensional list?
multilist = [['1', '2', 'Ham', '4'], ['5', 'ABCD', 'Foo'], ['Bar', 'Lu', 'Shou']]
counter = 0
for minilist in multilist:
for value in minilist:
counter += 1
print(counter)
I'm pretty sure there is a much simpler way to find the length of a multi-dimensional list, but len(list) does not work, as it only gives the number of lists inside. Is there a more efficient method than this?
How about:
sum(len(x) for x in multilist)
Alternative to #mgilson's solution
sum(map(len, multilist))
If you want the number of items in any n-dimensional list then you need to use a recursive function like this:
def List_Amount(List):
return _List_Amount(List)
def _List_Amount(List):
counter = 0
if isinstance(List, list):
for l in List:
c = _List_Amount(l)
counter+=c
return counter
else:
return 1
This will return the number of items in the list no matter the shape or size of your list
Another alternative (it's this or watch missed math lectures...)
def getLength(element):
if isinstance(element, list):
return sum([getLength(i) for i in element])
return 1
This allows different degrees of 'multi-dimensionality' (if that were a word) to coexist.
eg:
>>> getLength([[1,2],3,4])
4
Or, to allow different collection types
def getLength(element):
try:
element.__iter__
return sum([getLength(i) for i in element])
except:
return 1
eg:
>>> getLength([ 1, 2, (1,3,4), {4:3} ])
6
>>> getLength(["cat","dog"])
2
(Noting that although strings are iterable, they do not have the __iter__ method-wrapper and so will not cause any issues...)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Flatten (an irregular) list of lists in Python
I have a list in python like
l=[1,2,[3,4,5],[[4,2,4],[4,7,8]]]
I want using a set to get all unique values, but this fails
set(l)
TypeError: unhashable type: 'list'
So anybody help please? Want to use set with list of list of list etc etc THX
You'll need to 'unwind', or flatten the nested structure before you can put this in a set. You can use a generator for that to keep this efficient for large lists:
def flatten(lst):
for element in lst:
if isinstance(element, list):
for subelement in flatten(element):
yield subelement
else:
yield element
then use that generator on your list l to create a set:
set(flatten(l))
How about this approach, you flatten the list first before you apply the set operation on it.
import collections
def flat_list(tlist):
if isinstance(tlist, collections.Iterable):
return [j for i in tlist for j in flat_list(i)]
else:
return [tlist]
then:
myl=[1,2,[3,4,5],[[4,2,4],[4,7,8]]]
print set(flat_list(myl))
gives:
set([1, 2, 3, 4, 5, 7, 8])
#MartijnPieters approach with a generator will work more efficiently with very large lists than this list comprehension based approach.
This question already has answers here:
How do I get the number of elements in a list (length of a list) in Python?
(11 answers)
Closed 6 years ago.
I am trying to find a simple way of getting a count of the number of elements in a list:
MyList = ["a", "b", "c"]
I want to know there are 3 elements in this list.
len()
>>> someList=[]
>>> print len(someList)
0
just do len(MyList)
This also works for strings, tuples, dict objects.
len(myList) should do it.
len works with all the collections, and strings too.
len()
it will count the element in the list, tuple and string and dictionary,
eg.
>>> mylist = [1,2,3] #list
>>> len(mylist)
3
>>> word = 'hello' # string
>>> len(word)
5
>>> vals = {'a':1,'b':2} #dictionary
>>> len(vals)
2
>>> tup = (4,5,6) # tuple
>>> len(tup)
3
To learn Python you can use byte of python , it is best ebook for python beginners.
To find count of unique elements of list use the combination of len() and set().
>>> ls = [1, 2, 3, 4, 1, 1, 2]
>>> len(ls)
7
>>> len(set(ls))
4
You can get element count of list by following two ways:
>>> l = ['a','b','c']
>>> len(l)
3
>>> l.__len__()
3
Len won't yield the total number of objects in a nested list (including multidimensional lists). If you have numpy, use size(). Otherwise use list comprehensions within recursion.