简体   繁体   English

将多级列表中的“0”和“1”字符串转换为整数

[英]Convert “0” and “1” strings in a multi-level list to integers

I have a 3 level list of strings and need to convert the "0" and "1" strings into integers.我有一个 3 级字符串列表,需要将“0”和“1”字符串转换为整数。 I tried it like this but I am not getting the wanted result我像这样尝试过,但没有得到想要的结果

for list in a:
    for sublist in list:
        for item in sublist:    
            if item == "0" or item == "1":
                item == int(item)

What am I missing?我错过了什么? I tested it in different ways and I suspect the last line of code is wrong.我以不同的方式对其进行了测试,我怀疑最后一行代码是错误的。

You have to assign the converted item back to the original sub-sub list.您必须将转换后的项目分配回原始子子列表。 All you have done so far is assign it to a temporary variable that gets overwritten on the next iteration.到目前为止,您所做的只是将其分配给一个临时变量,该变量会在下一次迭代中被覆盖。

Also, try to avoid using list as a variable.另外,尽量避免使用list作为变量。

Try this:尝试这个:

for sublist in a:
    for subsublist in sublist:
        for i, item in enuerate(subsublist):    
            if item == "0" or item == "1":
                subsublist[i] = int(item)

recursive ver.递归版

def foo(l):
  res = []
  for ele in l:
    if type(ele) == list:
      res += foo(ele)
    else:
      if ele in ['1','0']:
        res += [int(ele)]
      else:
        res += [ele]
  return res

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

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