简体   繁体   English

Python:列表列表,从字符串更改为整数

[英]Python: List of Lists, Change from Strings to Ints

x =[['+1', '+2', '+3', '+4', '+5', '+6']] 

y = [['+1', '-3', '-6', '-5'], ['+2', '-4']]

Is there anyway to change my list of lists from Strings to Integers? 无论如何,我的列表列表从字符串更改整数?

I tried 我试过了

def changy(foo):
    new = []
    for i in xrange(len(foo)):
        r = map(int, foo[i])
        new.append(r)
    return new
changy(x)

when I run 当我跑步时

print changy(y)

my output is exactly what I want 我的输出正是我想要的

[[1, -3, -6, -5], [2, -4]]

whenever I run x I get 每当我跑x我得到

ValueError: invalid literal for int() with base 10: '+' ValueError:int()以10为底的无效文字:'+'

Any help is appreciated 任何帮助表示赞赏

ValueError: invalid literal for int() with base 10: '+' means that you're first iterating the main list, then the nested list and then the characters in the string itself; ValueError: invalid literal for int() with base 10: '+'表示您首先要迭代主列表,然后是嵌套列表,然后是字符串本身中的字符; that's one level "too far"/deep. 那是“太远” /太深的一个级别。

You can use a two-dimensional list comprehension. 您可以使用二维列表推导。 int() correctly interprets "+" and "-" as meaning positive and negative numbers: int()正确地将“ +”和“-”解释为正数和负数:

>>> y = [['+1', '-3', '-6', '-5'], ['+2', '-4']]
>>> [[int(d) for d in z] for z in y]
[[1, -3, -6, -5], [2, -4]]
>>> 

You can use map in this way as well: 您也可以通过以下方式使用map

>>> y = [['+1', '-3', '-6', '-5'], ['+2', '-4']]
>>> [map(int,z) for z in y]
[[1, -3, -6, -5], [2, -4]]
>>> 
def changy(n):
    return [[int(d) for d in z] for z in n]

print changy(x)    
[[1, 2, 3, 4, 5, 6]]

print changy(y)
[[1, -3, -6, -5], [2, -4]]

n = (a nested list) n =(嵌套列表)

the above comment helped me realized I was iterating to far into my list. 上面的评论使我意识到,我要反复进行下去。

This function helped me change my String nested lists to Integer nested lists. 此函数帮助我将String嵌套列表更改为Integer嵌套列表。

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

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