Seagan Damian
Seagan Damian

Reputation: 21

How to add specific characters of an elements of a list to a tuple

I have a list containing some elements that looks like this:

data = ["1: 6987", "2: 5436", "7: 9086"]

Is it possible to tuple the elements where it would look like this:

tuple_data = [("1", 6987) , ("2", 5436), ("7", 9086)]

Upvotes: 0

Views: 64

Answers (4)

davidshere
davidshere

Reputation: 396

splits = [record.split(": ") for record in data]
tuple_data = [(first, int(second)) for first, second in splits]

Can also do it in one line if you like:

tuple_data = [(first, int(second)) for first, second in [record.split(": ") for record in data]]

Upvotes: 2

DannyMoshe
DannyMoshe

Reputation: 6265

You can use a list comprehension:

data = [(i[:i.find(':')], int(i[i.find(':')+1:].strip())) for i in data]

result:

[('1', 6987), ('2', 5436), ('7', 9086)]

Upvotes: 0

jpp
jpp

Reputation: 164773

List comprehension is one way:

data = ["1: 6987", "2: 5436", "7: 9086"]

res = [(i.split(':')[0], int(i.split(':')[1])) for i in data]

# [('1', 6987), ('2', 5436), ('7', 9086)]

Syntax is simpler if you want only integers:

res = [tuple(map(int, i.split(':'))) for i in data]

# [(1, 6987), (2, 5436), (7, 9086)]

Upvotes: 0

evophage
evophage

Reputation: 169

map and split can be used for this:

 data = ["1: 6987", "2: 5436", "7: 9086"]
 map(lambda i: (i.split(': ')[0], int(i.split(': ')[1])), data)

Result:

 [('1', 6987), ('2', 5436), ('7', 9086)]

lambda defines an anonymous function which splits each element on ': ' and adds the first and second part of that split to a tuple, while map applies the anonymous (lambda) function to each element in data.

There may be a more elegant way :).

Upvotes: 1

Related Questions