Reputation: 7980
i have a 'dictionary-valueiterator' Groups. For each list of Groups i random sample two (or more values) and i store in a new list
GroupsList = list([])
for m in Groups:
GroupsList.append(point_random_selection(m,n))
where point_random_selection
def point_random_selection(list,n):
if n == 0:
raise TypeError("The pulse density 0 is not iterable")
try:
sample_point = random.sample(list,n)
except ValueError:
sample_point = list
return sample_point
GroupsList = [[<liblas.point.Point object at 0x00000001363A0E10>],
[<liblas.point.Point object at 0x00000002CE52CB38>],
[<liblas.point.Point object at 0x00000000CF516908>],
[<liblas.point.Point object at 0x00000004293F9400>],
[<liblas.point.Point object at 0x0000000249F67C50>],
[<liblas.point.Point object at 0x0000000312D85A90>],
[<liblas.point.Point object at 0x000000047DF396A0>,
<liblas.point.Point object at 0x000000047DF14F98>]]
where in some case i have two or more list (ex:)
GroupsList[6]
[<liblas.point.Point object at 0x000000047DF396A0>,
<liblas.point.Point object at 0x000000047DF14F98>]
I wish to store one list-by-one list in the new list in order to append one-by-one also when i have two or more liblas.point.Point object as:
GroupsList = [[<liblas.point.Point object at 0x00000001363A0E10>],
[<liblas.point.Point object at 0x00000002CE52CB38>],
[<liblas.point.Point object at 0x00000000CF516908>],
[<liblas.point.Point object at 0x00000004293F9400>],
[<liblas.point.Point object at 0x0000000249F67C50>],
[<liblas.point.Point object at 0x0000000312D85A90>],
[<liblas.point.Point object at 0x000000047DF396A0>],
[<liblas.point.Point object at 0x000000047DF14F98>]]
Is it a List Comprehensions the best approach? ex to insert in
GroupsList.append(point_random_selection(m,n))
Upvotes: 0
Views: 167
Reputation: 208625
If I understand this correctly, you want to change a nested list like [[a, b], [c, d]]
into [a, b, c, d]
using a list comprehension. If that is the correct interpretation for what you are trying to do, the following will work:
GroupsList = [point for lst in GroupsList for point in lst]
However it would be better to just create the flat structure from the beginning by changing your loop to the following (replacing append()
with extend()
):
for m in Groups:
GroupsList.extend(point_random_selection(m,n))
a.extend(b)
(where a
and b
are lists) results in the same behavior as the following loop (but does it more efficiently):
for x in b:
a.append(x)
Upvotes: 2
Reputation: 28856
I'm not entirely sure I'm reading your question correctly, but are you looking for list.extend
? For example:
>>> a = [1, 2]
>>> a.extend([5, 1, 4])
>>> a
[1, 2, 5, 1, 4]
Also, some general style feedback:
Group
or GroupsList
; name them groups
or groups_list
.list([])
is more easily written as just []
point_random_selection
list
should probably be avoided, since it shadows the global list()
functionpoint_random_selection
byreturn random.sample(the_list, min(n, len(the_list))
Upvotes: 1