Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
更改列表列表中的类型(Python)_Python_List_Types - Fatal编程技术网

更改列表列表中的类型(Python)

更改列表列表中的类型(Python),python,list,types,Python,List,Types,因此,我有一个函数,它获取列表列表,并根据值所表示的内容更改每个值的类型: def change_list(x): """ Convert every str in x to an int if it represents a integer, a float if it represents a decimal number, a bool if it is True/False, and None if it is either 'null' or an e

因此,我有一个函数,它获取列表列表,并根据值所表示的内容更改每个值的类型:

def change_list(x):
    """
    Convert every str in x to an int if it represents a
    integer, a float if it represents a decimal number, a bool if it is 
    True/False, and None if it is either 'null' or an empty str

    >>> x = [['xy3'], ['-456'], ['True', '4.5']]
    >>> change_list(x)
    >>> x
    [['xy3' , -456], [True], [4.5]]
    """
    for ch in x:
        for c in ch:
            if c.isdigit() == True:
                c = int(c)
我只发布了部分代码,我觉得一旦我能够排序,我就可以在其他if/elif/else中应用类似的方法,以便能够将所有内容都弄清楚。我的问题是,当我应用这种方法,然后再次调用x时,列表仍然作为字符串返回,而不是int、float或bools

即如果我在执行此函数后调用x,我将得到:

x = [['xy3'], ['-456'], ['True', '4.5']]
而不是函数中示例代码中的内容。
我不确定出了什么问题,任何建议都会有帮助。

您需要更改列表元素本身,而不是本地引用
c
ch

for i,ch in enumerate(x):
    if ch ... # whatever logic
        x[i] = ... # whatever value

您没有更新列表。你只是给这个值赋了另一个值,没有什么作用。使用
枚举
函数及其提供的索引值,然后使用索引更改该值

for ch in x:
    for c in ch:
        if c.isdigit() == True:
            c = int(c) # You're doing 'xyz' = int('xyz') which does nothing
更好的是,由于您希望基于当前列表生成一个新列表,因此最好使用
map

inp_list = [...] # Your list
out_list = list(map(lambda nums: int(n) for n in nums if n.isDigit(), inp_list))
# The above is for only integer conversion but you get the idea. 

当前您正在使用列表的值,但未更新它。因此,您需要枚举它,并通过引用直接更改列表元素

正确的代码如下所示:

for idx,ch in enumerate(x):
    for idx2,c in enumerate(ch):
        if c.isdigit() == True:
            x[idx][idx2] = int(c)

isdigit
isnumeric
将不起作用,因为'-456'包含
-
和'4.5'包含'

相反,你应该:

x = [['xy3'], ['-456'], ['True', '4.5'], ['3']]
for ch in x:
    for i in range(len(ch)):
        try:
            ch[i] = float(ch[i])
            if int(ch[i]) == ch[i]:
                ch[i] = int(ch[i])
        except:
            if ch[i] in ['True', 'False']:
                ch[i] = (['True', 'False'][0] == ch[i]) 
print(x)   
输出

[['xy3'], [-456], [True, 4.5]]
因为当你这样做的时候:

for ch in x:
    for c in ch:
        if c.isdigit() == True:
            c = int(c)    #yes it changed the type but it doesn't stroed in list 
是的,您正在更改类型,但您将更改的内容存储在哪里

为此,您必须告诉列表在该索引处更改,为此,您可以使用enumerate:

item[index]=int(item1)
第二件事是在float上使用isdigit(),它将不起作用:

str.isdigit()仅当字符串中的所有字符 是数字。和-是标点符号,不是数字

因此,您可以尝试以下两种方法:

第一种方法:

输出:

[['xy3'], [-456], ['True', 4.5]]
[['xy3'], [-456], ['True', 4.5]]
或者,如果需要,可以将所有int转换为float:

x = [['xy3'], ['-456'], ['True', '4.5']]
for item in x:
    if isinstance(item,list):
        for index,item1 in enumerate(item):
            if item1.replace("-","").replace(".","").isdigit():
                item[index]=float(item1)

print(x)
第二种方法:

您可以定义自己的
isdigit()
函数:

x = [['xy3'], ['-456'], ['True', '4.5']]
def isdigit(x):
    try:
        float(x)
        return True
    except ValueError:
        pass
然后一行解决方案:

详细解决方案:

输出:

[['xy3'], [-456], ['True', 4.5]]
[['xy3'], [-456], ['True', 4.5]]

首先:isdigit为负值返回false,这就是你不能得到X中整数的原因

>>> x[1][0].isdigit()
False
: 在
c=int(c)

工作示例如下所示: 调查
>>> x[1][0].isdigit()
False
x = [['xy3'], ['-456'], ['True', '4.5']]
for index, value in enumerate(x):
     for i,v in enumerate(value):
         try:
             x[index][i] = eval(v)
         except:
             pass