Python go from a list of tuple to a list of integer without quotes

53 Views Asked by At

I have this code :

selected_listbox_select_criteria_column = [('0', 'firstName'),('1', 'lastName'),('2', 'phone')]

column_to_check_for_criteria = []

column_to_check_for_criteria(', '.join(elems[0] for elems in selected_listbox_select_criteria_column))

It gives me this result :

['0,1,2']

How can I have a strict list of integer like this :

[0,1,2] 

without the quotes to finally get equivalent of : column_to_check_for_criteria = [0,1,2]

Thanks

4

There are 4 best solutions below

1
idjaw On BEST ANSWER

The issue you are facing is the additional work you don't need to be doing with your ', '.join(...) call. It seems what you are trying to do is to simply extract in to a list the integer values as integer type from your list of tuples. To do this, based on the code you are writing, you don't need to use that join. You can simply use a list comprehension and cast each elems[0] to int. This should give you the expected output:

selected_listbox_select_criteria_column = [('0', 'firstName'),('1', 'lastName'),('2', 'phone')]

column_to_check_for_criteria = [int(elems[0]) for elems in selected_listbox_select_criteria_column]

Running that will now give you

[0, 1, 2]

As added information, you would typically use a join when you want to turn a list in to a string. An extra little note about using join is that expects an iterable of type string and not int. You can't actually use it on a list of integers. Observe the following two examples:

This will fail

a = [1, 2, 3]
print(",".join(a))

This will not

a = ["a", "b", "c"]
print(",".join(a))
0
user16171413 On

You can loop through the original list using list comprehension and convert the first element in each tuple to integer using int function:

column_to_check_for_criteria = [int(i[0]) for i in selected_listbox_select_criteria_column]

Output: [0, 1, 2]

0
degD On

Maybe you can convert numbers (str) to int. Something like this:

selected_listbox_select_criteria_column = [('0', 'firstName'),('1', 'lastName'),('2', 'phone')]

column_to_check_for_criteria = [int(elems[0]) for elems in selected_listbox_select_criteria_column]
0
sahasrara62 On

using map you can achive this as

>>> tuple_list = [('0', 'firstName'),('1', 'lastName'),('2', 'phone')]
>>> int_list = list(map(lambda x : int(x[0]), tuple_list))
>>> int_list
[0, 1, 2]

more simple way will be use list comprehension as

int_list = [int(int_val) for int_val, string in tuple_list]