List Comprehension on a Nested List

List comprehension on a nested list?

Here is how you would do this with a nested list comprehension:

[[float(y) for y in x] for x in l]

This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use [float(y) for x in l for y in x].

How to make a nested list comprehension?

result = [item for row in prices for item in row]
print(result)

List comprehension to access a nested list within a list only in one index

So, if you have something like the following:

distances = [
('highway_bost321', [0.0, 10.174343253183386, 10.947746706490813, 7.187637514988234, 7.660483562939873, 10.622402335214636, 10.737785768990813, 10.566917715980832, 10.819389772897063, 12.03400784892136]),
('mountain_0871', [10.947746706490813, 0.83758544921875, 0.0, 5.838234191502578, 5.363256367154217, 1.3175048828125, 3.0810546875, 6.634500456993904, 0.78460693359375, 13.91981431878607]),
('opencountry_043', [7.660483562939873, 4.668136048210366, 5.363256367154217, 2.8142531243329643, 0.0, 5.347678752303554, 3.236628762987552, 5.377074226549635, 5.634096535101808, 13.405988675235129]),
('opencountry_053', [10.622402335214636, 0.73712158203125, 1.3175048828125, 5.876377140065916, 5.347678752303554, 0.0, 3.1134033203125, 6.11476575647307, 1.97711181640625, 13.144871284931902]),
('opencountry_123', [10.737785768990813, 3.01690673828125, 3.0810546875, 5.560564920669245, 3.236628762987552, 3.1134033203125, 0.0, 5.71620618616057, 3.09417724609375, 13.597874214619402]),
('palace_019', [10.566917715980832, 5.890665007775154, 6.634500456993904, 3.7392389463104037, 5.377074226549635, 6.11476575647307, 5.71620618616057, 0.0, 6.493675414476205, 12.731745772059295]),
('volcano_010', [10.819389772897063, 1.294677734375, 0.78460693359375, 5.709877257908828, 5.634096535101808, 1.97711181640625, 3.09417724609375, 6.493675414476205, 0.0, 13.90083238519232]),
('waterfall03', [12.03400784892136, 13.17207261956732, 13.91981431878607, 13.095577523116825, 13.405988675235129, 13.144871284931902, 13.597874214619402, 12.731745772059295, 13.90083238519232, 0.0])
]

sample = [
('highway_bost321', 0),
('mountain_0871', 2),
('opencountry_043', 4),
('opencountry_053', 5),
('opencountry_123', 6),
('palace_019', 7),
('volcano_010', 8),
('waterfall03', 9)
]

then you can use something like:

result = [
(k, vs[:index] + vs[index+1:]) for (key, index) in samples
for k, vs in distances if k == key
]

Which gets you:

[('highway_bost321', [10.174343253183386, 10.947746706490813, 7.187637514988234, 7.660483562939873, 10.622402335214636, 10.737785768990813, 10.566917715980832, 10.819389772897063, 12.03400784892136]),
('mountain_0871', [10.947746706490813, 0.83758544921875, 5.838234191502578, 5.363256367154217, 1.3175048828125, 3.0810546875, 6.634500456993904, 0.78460693359375, 13.91981431878607]),
('opencountry_043', [7.660483562939873, 4.668136048210366, 5.363256367154217, 2.8142531243329643, 5.347678752303554, 3.236628762987552, 5.377074226549635, 5.634096535101808, 13.405988675235129]),
('opencountry_053', [10.622402335214636, 0.73712158203125, 1.3175048828125, 5.876377140065916, 5.347678752303554, 3.1134033203125, 6.11476575647307, 1.97711181640625, 13.144871284931902]),
('opencountry_123', [10.737785768990813, 3.01690673828125, 3.0810546875, 5.560564920669245, 3.236628762987552, 3.1134033203125, 5.71620618616057, 3.09417724609375, 13.597874214619402]),
('palace_019', [10.566917715980832, 5.890665007775154, 6.634500456993904, 3.7392389463104037, 5.377074226549635, 6.11476575647307, 5.71620618616057, 6.493675414476205, 12.731745772059295]),
('volcano_010', [10.819389772897063, 1.294677734375, 0.78460693359375, 5.709877257908828, 5.634096535101808, 1.97711181640625, 3.09417724609375, 6.493675414476205, 13.90083238519232]),
('waterfall03', [12.03400784892136, 13.17207261956732, 13.91981431878607, 13.095577523116825, 13.405988675235129, 13.144871284931902, 13.597874214619402, 12.731745772059295, 13.90083238519232])]

But this is highly inefficient. This will be polynomial time. Notice the inner loop, k, vs in distances if k == key which is highly wastefull.

Instead, distances should be a dict,

distances = dict(distances)

then you can do:

{key: distances[key][:index] + distances[key][index+1:] for key, index in samples}

Create nested list using list comprehension

Create a nested list comprehension

>>> [[(x+y) for y in L1 if y < 4] for x in L2 if x < 4]
[[4, 4], [6, 6], [6, 6]]

Here the inner list comprehension creates the inner lists which are then appended to a single list by the outer comprehension.

Nested list comprehension on python

This should do it:

value = ['a','b','c','d','e','f']
key = [2, 3, 1, 1, 3, 2]

answer = {}
for k, v in zip(key, value):
if k in answer:
answer[k].append(v)
else:
answer[k] = [v]

print(answer)
{2: ['a', 'f'], 3: ['b', 'e'], 1: ['c', 'd']}

EDIT: oops, jumped the gun. Apologies.

Here's the comprehension version, but it's not very efficient:

{
k: [v for i, v in enumerate(value) if key[i] == k]
for k in set(key)
}

EDIT 2:

Here's an one that has better complexity:

import pandas as pd
series = pd.Series(key)
{
k: [value[i] for i in indices]
for k, indices in series.groupby(series).groups.items()
}

Nested list comprehension with if statement

you can rewrite this as follows:

new_list = [y for x in nested_list for d, y in enumerate(x) if d == 1]

loops are in the "natural" order, and the condition is in the end. Include y only if d==1

one possible result (because dicts aren't ordered):

[{'c': 3, 'd': 4}, {'c': 7, 'd': 8}]

Note that in your case, it's simpler and more efficient (O(n) vs O(n**2)) to write:

new_list = [x[1] for x in nested_list]

the only difference is that if x is too short the latter code will break so maybe test length:

new_list = [x[1] for x in nested_list if len(x)>1]

How to use a list comprehension to store the nested list of a list

try this:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
output = [item for sublist in nested_list for item in sublist]
print(output) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation:

When you use list comprehension for nested loops, the structure of the expression is as follows:

  • The leftmost expression, item, is what will contain the returned list.
  • The first loop from left is the most outer loop, for sublist in nested_list so first you iterate over the each element in your input list and name it sublist.
  • The right most loop, for item in sublist is the most inner loop. In your case this loops iterates over each element of the sublist and name it item which will eventually will be returned in the output.

How can i create this nested list using list comprehension?

You can use to_dict:

>>> df
0 1 2 3 4
0 Date0 Date1 Date2 Date3 Date9
1 GMV0 GMV1 GMV2 GMV3 GMV9
2 Revenue0 Revenue1 Revenue2 Revenue3 Revenue9

>>> list(df.to_dict(orient='list').values())

[['Date0', 'GMV0', 'Revenue0'],
['Date1', 'GMV1', 'Revenue1'],
['Date2', 'GMV2', 'Revenue2'],
['Date3', 'GMV3', 'Revenue3'],
['Date9', 'GMV9', 'Revenue9']]

Update

>>> df
Date0 Date1 Date2 Date3 GMV0 GMV1 GMV2 GMV3 Revenue0 Revenue1 Revenue2 Revenue3
0 A B C D E F G H I J K L


>>> [list(t.columns) for _, t in df.groupby(df.columns.str.extract(r'(\d+)', expand=False), axis=1)]

[['Date0', 'GMV0', 'Revenue0'],
['Date1', 'GMV1', 'Revenue1'],
['Date2', 'GMV2', 'Revenue2'],
['Date3', 'GMV3', 'Revenue3']]

Explanation of how nested list comprehension works?

Ah, the incomprehensible "nested" comprehensions. Loops unroll in the same order as in the comprehension.

[leaf for branch in tree for leaf in branch]

It helps to think of it like this.

for branch in tree:
for leaf in branch:
yield leaf

The PEP202 asserts this syntax with "the last index varying fastest" is "the Right One", notably without an explanation of why.



Related Topics



Leave a reply



Submit