简体   繁体   English

将元素列表转换为int而不是python中的字符串

[英]convert list of element to int and not the string in python

I wish to convert this list to int and not the element of string inside it. 我希望将此列表转换为int而不是其中的字符串元素。

just to convert those are integer. 只是将其转换为整数。

a = ["a\\n", "222\\n", "bbb\\n", "7777"] a = [“ a \\ n”,“ 222 \\ n”,“ bbb \\ n”,“ 7777”]

is there a way to do so? 有办法吗?

I tried 我试过了

for x in a:
   x = int(a)

but this convert all. 但这会全部转换。

Not sure what is your expectation. 不知道您的期望是什么。 But I think you are having the string in your list so you are getting the string. 但是我认为您在列表中有该字符串,因此可以获取该字符串。 Try the below and check if this helps. 请尝试以下操作,并检查是否有帮助。

#this is all string
#a = ["a\n", "222\n", "bbb\n", "7777"]

#try with the below set
a = [10,11,'1','a','b',12,13,'14','c']

intPart = [x for x in a if isinstance(x, int)]
stringPart = [x for x in a if isinstance(x, str)]

print(intPart)
print(stringPart)

#output
#10, 11, 12, 13]                                                                                                                                               
#['1', 'a', 'b', '14', 'c']  

You can attempt a conversion, and return the value unchanged if it's not possible: 您可以尝试进行转换,如果不可能,则返回不变的值:

def to_int(x):
    try:
        return int(x)
    except ValueError:
        return x

a = ["a\n", "222\n", "bbb\n", "7777"]
new_a = [to_int(x) for x in a]
print(new_a)

Output: 输出:

['a\n', 222, 'bbb\n', 7777]

Edited: I did not quite understood what OP mean by "convert this list to int" 编辑:我不太了解OP的“将列表转换为int”的含义

I suppose you want: 我想你要:

a = ["a\n", "222\n", "bbb\n", "7777"]

[ int(el) if el.isnumeric() else el     
   for el in a 
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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