简体   繁体   English

从python列表中的元素中删除引号

[英]Removing quotes from elements in python list

I have a python list that looks like alist = ['4', '1.6', 'na', '2e-6', '42'] . 我有一个看起来像alist = ['4', '1.6', 'na', '2e-6', '42']的python列表。 If i want to remove the quotes from this and make it look like [4, 1.6, na, 2e-6, 42] , normally i use the following code : 如果我想从中删除引号并使它看起来像[4, 1.6, na, 2e-6, 42] ,通常我使用以下代码:

alist = [float(x) if type(x) is str else None for x in alist]

But this time, as I have the string 'na' as one of the elements in the list, this line of code will not work. 但是这一次,因为我将字符串'na'作为列表中的元素之一,所以这一行代码将不起作用。 Is there an elegant way to do this in python? 有没有在python中执行此操作的优雅方法?

Assuming you are happy to replace the value 'na' with None , or more generally, any non-float looking text with None , then you could do something like: 假设您很乐意用None替换值'na' ,或更一般地说,将所有非浮点型文本替换为None ,那么您可以执行以下操作:

def converter(x):
    try:
        return float(x)
    except ValueError:
        return None

alist = [converter(x) for x in alist]

This will convert anything to float that it can. 这会将任何东西转换为可以浮动的形式。 So, as it stands, this will also convert existing numbers to float: 因此,按现状,这还将把现有数字转换为浮点数:

>>> [converter(x) for x in ('1.1', 2, 'na')]
[1.1, 2.0, None]

When python lists, sets, dicts, etc are printed out, they are printed in the same format that python uses to compile the "raw code." 当打印出python列表,集合,字典等时,它们以python用于编译“原始代码”的相同格式打印。 Python compiles lists in quotes. Python编译带引号的列表。 So you just need to iterate over the list. 因此,您只需要遍历列表即可。

Simply use a generator expression to fix this (though it really doens't have much effect unless you are displaying on a tkinter widget or something): 只需使用生成器表达式即可解决此问题(尽管除非在tkinter小部件上显示,否则它实际上并没有多大作用):

>>> alist = ['4', '1.6', 'na', '2e-6', '42']    

>>> for a in alist:
...    print(a)

>>> 4
>>> 1.6
>>> na
>>> 2e-6
>>> 42

I'm not sure where the "na", "nan" confusion is coming from. 我不确定“ na”,“ nan”的混乱来自何处。 Regardless, if you want to lose the quotes, run your code through a generator expression and it will no longer be under the "list class" - hence, the quotes will no longer appear. 无论如何,如果您想丢失引号,请通过生成器表达式运行代码,该表达式将不再位于“列表类”下-因此,引号将不再出现。

The list elements are all still the same type, 列表元素仍然是同一类型,

edit: clarity, grammar 编辑:清晰度,语法

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

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