简体   繁体   中英

How to convert string in a tuple to an integer?

I scrape down stats that get put in a list that I later want to convert to a dictionary. The list looks like this:

 my_list = [('Appearances   ', '      32'),('Clean sheets   ', '      6'), etc,etc]

How do I convert the integers in the tuple to integers?

my_list = map(lambda x: [x[0], int(x[1].strip())], my_list)

给定OP规范的输入列表my_list ,返回结果列表,其中第二个值去除空格并变成整数。

The easy, generally-applicable method would be to convert anything numeric (strings have a test for this) into an integer. The slight trick to it is that the number string can't have spaces in it to check if it's numeric (but it can have them to convert to an integer).

So:

>>> listoftuples = [('Appearances   ', '      32'), ('Clean sheets   ', '      6')]
>>> [tuple(int(item) if item.strip().isnumeric() else item for item in group) for group in listoftuples]
>>> [('Appearances   ', 32), ('Clean sheets   ', 6)]

The advantage of this method is that it's not specific to your input. It works fine if the integer is first, or if the tuples are different lengths, etc.

您可以使用列表理解:

    new_list = [(x[0], int(x[1].strip())) for x in my_list]

The following code will convert the strings to integers. And, it will also create a dictionary using the list of tuples.

my_list = [
     ('Appearances   ', '      32'),
     ('Clean sheets   ', '      6')
]
d = dict()
for key, value in my_list:
    d[key.strip()] = int(value.strip())
print(d)

The above solution assumes each of the tuple in the list will have two elements key & value . All the first elements (keys) of the tuples are unique. And, the second elements (values) are strings that can be converted into integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM