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

2024-10-01 17:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

我只发布了部分代码,我觉得一旦我可以排序,我就可以在otherif/elif/else中应用一个类似的方法,以便能够把所有的代码都弄清楚。我的问题是,当我应用这种方法,然后再次调用x时,列表仍然以字符串形式返回,而不是int、float或bools。你知道吗

如果我在执行这个函数后调用x,我会得到:

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

而不是函数中示例代码中的内容。 我不确定出了什么问题,任何建议都会有帮助的。你知道吗


Tags: 函数代码inantrue内容列表if
3条回答

因为当你这么做的时候:

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() will only return true if all characters in the string are digits. . and - are punctuation, not a digit.

所以你可以试试这两种方法:

First Method :

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

print(x)

输出:

[['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)

Second Method:

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

x = [['xy3'], ['-456'], ['True', '4.5']]
def isdigit(x):
    try:
        float(x)
        return True
    except ValueError:
        pass

Then one line solution :

print([[float(item1) if '.' in item1 else int(item1)] if isdigit(item1)  else item1 for item in x if isinstance(item,list) for index,item1 in enumerate(item)])

Detailed Solution:

for item in x:
    if isinstance(item,list):
        for index,item1 in enumerate(item):
            if isdigit(item1)==True:
                if '.' in item1:
                    item[index]=float(item1)
                else:
                    item[index]=int(item1)

print(x)

输出:

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

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

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

你没有更新名单。你只是给这个值赋了另一个值,没有什么作用。使用enumerate函数及其提供的索引值,然后使用索引更改该值。你知道吗

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. 

相关问题 更多 >

    热门问题