0

I'm currently attempting to import a list of numbers from a csv file as tuples, to look like this:

[(60, 20), (100, 55), (50, 40), (20, 70), (95, 85)])

def tuples(filename):
    import csv
    with open(filename) as csvfile:
        rdr = csv.reader(csvfile)
        next(rdr, None) 
        my_list = [tuple(filter(None, row)) for row in rdr]
        print(my_list)

tuples("tuple.csv")

However at the moment my output is: [('60', '20'), ('100', '55'), ('50', '40'), ('20', '70', ' '), ('95', '85')]

How can I format my code to get rid of the quotation marks, and the empty field. Any help would be appreciated.

3 Answers3

1

Using list comprehensions (which is neater but harder to understand for a beginner), Iterate through all the values and convert each element to an integer if one exists

my_list = [('60', '20'), ('100', '55'), ('50', '40'), ('20', '70', ' '), ('95', '85')]
my_formatted_list = [tuple(int(value) for value in _tuple if value.strip()) for _tuple in my_list]
Tobey
  • 1,400
  • 1
  • 10
  • 25
0

If you want those values in a list of integers you could do

intlist = []
for i in my_list:
    intlist += int (i)
print (intlist)

This would output [(60, 20), (100, 55), (50, 40), (20, 70), (95, 85)])

If you want to output the values seperately you could just loop over your list like that

for i in my_list:
    print (int (i))

If you want it on one line try something like that

line = ""
for i in my_list:
    line += i
print (line)
0

You can use list comprehension with map() function like below:

my_list = [('60', '20'), ('100', '55'), ('50', '40'), ('20', '70', ' '), ('95', '85')]
[tuple(map(int, item[:2])) for item in my_list]
# Output: [(60, 20), (100, 55), (50, 40), (20, 70), (95, 85)]

Explanation:

map(int, item[:2]), map() is used to apply the function int() to each element of item[:2].

item[:2], to use only the 2 first elements of each tuple in my_list.

ettanany
  • 19,038
  • 9
  • 47
  • 63