Nested List Comprehension To Flatten Nested List
I'm quite new to Python, and was wondering how I flatten the following nested list using list comprehension, and also use conditional logic. nested_list = [[1,2,3], [4,5,6], [7,8,9
Solution 1:
Your syntax was a little wrong. Try below snippet.
nested_list = [[1,2,3], [4,5,6], [7,8,9]]
odds_evens = ['odd'if n % 2 != 0else'even'for l in nested_list for n in l]
print(odds_evens)
Output:
['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
Solution 2:
Read data from Nested list and output to a Flat list based on condition
nested_list = [[1,2,3], [4,5,6], [7,8,9]]
flat_list = [item forsublistin nested_list foritemin sublist]
# >>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
flat_list_even = [item forsublistin nested_list foritemin sublist if item % 2 == 0]
# >>> [2, 4, 6, 8]
flat_list_odd = [item forsublistin nested_list foritemin sublist if item % 2 != 0]
# >>> [1, 3, 5, 7, 9]
flat_list_literal = ["even"if item % 2 == 0else"odd"forsublistin nested_list foritemin sublist]
# >>> ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
Solution 3:
What is wrong here ?
>>>nested_list = [[1,2,3], [4,5,6], [7,8,9]]>>>odds_evens = ['odd'if n % 2 != 0else'even'for1in nested_list for n in1]
File "<stdin>", line 1
SyntaxError: can't assign to literal
Solution 4:
To create a flat list, you need to have one set of brackets in comprehension code. Try the below code:
odds_evens = ['odd' if n%2!=0 else 'even' for n in l for l in nested_list]
Output:
['odd', 'odd', 'odd', 'even', 'even', 'even', 'odd', 'odd', 'odd']
Post a Comment for "Nested List Comprehension To Flatten Nested List"