I have this array that contains some other arrays in Python, but I need only the first elements of each mini array inside the main array. Is there some method to do that?
Example:
array = [['a','1'], ['b','2'], ['c','3'], ['d','4'], ['e','5']]
I need the letters in one row:
'a'
'b'
'c'
'd'
'e'
And the numbers in another:
'1'
'2'
'3'
'4'
'5'
can You help me with this?
Djaouad
22.8k4 gold badges37 silver badges57 bronze badges
asked May 12, 2019 at 23:42
Carlos Aldair Guevara
352 silver badges7 bronze badges
-
2Possible duplicate of How to unzip a list of tuples into individual lists?Joseph Sible-Reinstate Monica– Joseph Sible-Reinstate Monica2019年05月12日 23:44:36 +00:00Commented May 12, 2019 at 23:44
3 Answers 3
You can use zip to separate letters from numbers and map to convert the tuples returned by zip to lists:
array = [['a','1'], ['b','2'], ['c','3'], ['d','4'], ['e','5']]
letters, numbers = map(list, zip(*array))
print(letters)
print(numbers)
Output:
['a', 'b', 'c', 'd', 'e']
['1', '2', '3', '4', '5']
answered May 12, 2019 at 23:49
Djaouad
22.8k4 gold badges37 silver badges57 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can use comprehension. a[0] means first item in a list
[a[0] for a in array]
Result:
['a', 'b', 'c', 'd', 'e']
answered May 12, 2019 at 23:46
jose_bacoy
12.7k1 gold badge25 silver badges41 bronze badges
3 Comments
jose_bacoy
welc. glad to help!
Carlos Aldair Guevara
Hey, hi again! Do you know how add an '\n' to each element?
jose_bacoy
a[0]+'\n'. this will add a new line
You can use
letters,numbers = tuple(zip(*array))
answered May 12, 2019 at 23:50
Reiner Czerwinski
2961 silver badge4 bronze badges
Comments
lang-py