1

How do you turn a list that contain pairs into a list that contains tuple pairs by using easy programming e.g for loop? x,y = ...?

My code:

def read_numbers():
    numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
    numbers.split(',')
    x,y = tuple numbers
    return numbers

desire output:

[(68,125), (113,69), (65,86), (108,149), (152,53), (78,90)]
S.Jackson
  • 23
  • 3

4 Answers4

2
def read_numbers():
    numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
    return [tuple(map(int,pair.split(','))) for pair in numbers]
control_fd
  • 348
  • 2
  • 8
2

Try this by using nested list comprehension:

o = [tuple(int(y) for y in x.split(',')) for x in numbers]
2342G456DI8
  • 1,819
  • 3
  • 16
  • 29
  • 1
    You can omit the `[]` brackets in the `tuple` constructor. No need build a `list`, just pass the generator expression. – user2390182 May 30 '16 at 07:09
1

Just use list comprehension. Read more about it here!

# Pass in numbers as an argument so that it will work
# for more than 1 list.
def read_numbers(numbers):
    return [tuple(int(y) for y in x.split(",")) for x in numbers]

Here is a breakdown and explanation (in comments) of the list comprehension:

[
    tuple(                              # Convert whatever is between these parentheses into a tuple
            int(y)                      # Make y an integer
            for y in                    # Where y is each element in
            x.split(",")                # x.split(","). Where x is a string and x.split(",") is a list
                                        # where the string is split into a list delimited by a comma.
    ) for x in numbers                  # x is each element in numbers
]

However, if you are just doing it for one list, there is no need to create a function.

Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38
  • You can omit the `[]` brackets in the `tuple` constructor. No need build a `list`, just pass the generator expression. – user2390182 May 30 '16 at 07:09
0

Try this :

def read_numbers():
    numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
    final_list = []
    [final_list.append(tuple(int(test_str) for test_str in number.split(','))) for number in numbers]
    return final_list
NSM
  • 31
  • 5