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

标签 python list

我希望将此列表转换为 int,而不是其中的 string 元素。

只是为了将它们转换为整数。

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

有办法吗?

我试过了

for x in a:
   x = int(a)

但这会全部转换。

最佳答案

不确定您的期望是什么。但我认为您的列表中有该字符串,因此您正在获取该字符串。尝试以下方法并检查是否有帮助。

#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']  

关于python - 将元素列表转换为 int 而不是 python 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54318706/

相关文章:

python - 如何将 Unicode 字符串转换为字典?

Python:具有均值和标准差的随机数生成器

list - Erlang 中的映射函数

c - C 中 ADT 列表迭代器的问题

python - O(n) 时间内的滑动窗口最大值

javascript - 过滤后的 HTML 列表 : making li elements initially invisible

python - 使用元组作为 json.dump 嵌套属性的键

python - 更改 Pandas MultiIndex DataFrame 中的特定列值

python - 在启动时将 python 脚本作为守护进程运行 (Ubuntu)

python - 嵌套链与重复信息