How to Get First Element in a List of Tuples

How to get first element in a list of tuples?

>>> a = [(1, u'abc'), (2, u'def')]
>>> [i[0] for i in a]
[1, 2]

Get the first element of each tuple in a list in Python

Use a list comprehension:

res_list = [x[0] for x in rows]

Below is a demonstration:

>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>

Alternately, you could use unpacking instead of x[0]:

res_list = [x for x,_ in rows]

Below is a demonstration:

>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> [x for x,_ in lst]
[1, 3, 5]
>>>

Both methods practically do the same thing, so you can choose whichever you like.

Get all first element of tuples from list of lists of tuples in Python

output = [[item[0] for item in order] for order in orders]

display(output)

[['Fries'],
['Burger', 'Milkshake', 'Cola'],
['Cola', 'Nuggets', 'Onion Rings'],
['Fries'],
['Big Burger', 'Nuggets']]

How to get the first items from a list of tuples when each item is also wrapped in another tuple

Assuming this is Python, you can use a list comprehension. You will need to extract the first (only) value of the first element in each tuple:

res = [i[0][0] for i in test]

# ['over1.5', 'ht1over0.5', 'hgover0.5', 'over2.5', 'agover0.5']

How to get first item of each tuple in a list / python

List comprehension:

my_new_list = [key for key, value in my_list]

Or just produce a list of keys in the first place:

my_new_list = sorted(index_dict, key=index_dict.get, reverse=True)

Get the first elements of a list of tuples

Since you already know how to find the correct answer for a single element, all you need is a little recursion

func :: [(Int, a)] -> [a]
func [] = []
func ((n, elem):rest) = (replicate n elem) ++ (func rest)

Mapping the values should also work. You just need to concatenate the resulting strings into one.

func :: [(Int, a)] -> [a]
func xs = concat $ map func2 xs where
func2 (n, elem) = replicate n elem

Or, if you are familiar with currying:

func :: [(Int, a)] -> [a]
func xs = concat $ map (uncurry replicate) xs

Finally, if you are comfortable using function composition, the definition becomes:

func :: [(Int, a)] -> [a]
func = concat . map (uncurry replicate)

Using concat and map is so common, there is a function to do just that. It's concatMap.

func :: [(Int, a)] -> [a]
func = concatMap (uncurry replicate)

How to extract 1st element from list of tuples in Python

>>> lst = [(163.0, 0.5), (161.0, 0.5), (158.0, 1.0), (157.0, 1.0), (156.0, 2.0), (154.0, 1.0), (151.0, 0.5), (145.0, 1.0), (143.0, 0.5), (142.0, 0.5), (138.0, 0.5), (136.0, 1.0), (134.0, 1.0), (131.0, 1.0), (124.0, 1.0), (121.0, 1.0), (119.0, 1.0), (115.0, 1.0), (110.0, 1.0), (106.0, 0.5), (103.0, 0.5), (98.0, 1.0), (87.0, 1.0), (84.0, 1.0), (76.0, 2.0), (71.0, 1.0), (62.0, 1.0), (59.0, 1.0), (53.0, 1.0), (45.0, 1.0), (41.0, 1.0), (36.0, 1.0), (33.0, 1.0), (32.0, 1.0), (22.0, 1.0), (21.0, 1.0), (16.0, 1.0), (14.0, 1.0), (9.0, 1.0), (5.0, 1.0)]
>>> stresses = [a for a, _ in lst]
>>> stresses
[163.0, 161.0, 158.0, 157.0, 156.0, 154.0, 151.0, 145.0, 143.0, 142.0, 138.0, 136.0, 134.0, 131.0, 124.0, 121.0, 119.0, 115.0, 110.0, 106.0, 103.0, 98.0, 87.0, 84.0, 76.0, 71.0, 62.0, 59.0, 53.0, 45.0, 41.0, 36.0, 33.0, 32.0, 22.0, 21.0, 16.0, 14.0, 9.0, 5.0]

Get index of a list with tuples in which the first element of the tuple matches pattern

You can use enumerate() to find your index:

Try:

idx = next(i for i, (v, *_) in enumerate(countries) if v == "Brazil")
print(idx)

Prints:

2

extract each first item from list of tuples in pandas column

Use Series.apply to apply the logic row-wise to every element of 'col' column, and create the extra columns. Finally, use DataFrame.join to add those extra columns to the original DataFrame

import pandas as pd
import numpy as np
from collections import Counter

df = \
pd.DataFrame(columns=['date', 'col'],
data = [["2009-09-01", [(201, 0, 2), (206, 4, 6), (206, 6, 8)]],
["2009-09-01", [(206, 1, 3)]],
["2009-09-01", np.NaN],
["2009-09-01", [(201, 0, 2), (201, 4, 6, ), (202, 7, 9)]],
["2009-09-01", [(202, 0, 2), (203, 4, 6, ), (204, 7, 9)]],
["2009-09-01", [(202, 0, 2), (202, 4, 6, ), (202, 7, 9)]]])

# create a set instead of a list for O(1) membership test
values = {201, 202, 203, 204, 205, 206}
# to rename columns as in the example
column_mapper = dict(zip(sorted(values), "abcdef"))

def count_values(lst):
# initialize the counts to zero for every element of values
counts = Counter({n: 0 for n in values})
if lst is np.nan:
return pd.Series(counts) # if it's Nan return zero counts
# update the counts based on first element of each tuple
counts.update(x for x, *_ in lst if x in values)
return pd.Series(counts)

df = (
df.join(df['col'].apply(count_values))
.rename(columns=column_mapper) # optional columns renaming
)

Output

>>> df

date col a b c d e f
0 2009-09-01 [(201, 0, 2), (206, 4, 6), (206, 6, 8)] 1 0 0 0 0 2
1 2009-09-01 [(206, 1, 3)] 0 0 0 0 0 1
2 2009-09-01 NaN 0 0 0 0 0 0
3 2009-09-01 [(201, 0, 2), (201, 4, 6, ), (202, 7, 9)] 2 1 0 0 0 0
4 2009-09-01 [(202, 0, 2), (203, 4, 6, ), (204, 7, 9)] 0 1 1 1 0 0
5 2009-09-01 [(202, 0, 2), (202, 4, 6, ), (202, 7, 9)] 0 3 0 0 0 0


Related Topics



Leave a reply



Submit