【问题标题】:How to change a string in a list into integers [duplicate]如何将列表中的字符串更改为整数[重复]
【发布时间】:2021-04-16 15:02:01
【问题描述】:

我需要将字符串列表转换为整数。

示例:[['1,2'],['3,4']]

想要的结果是[[1,2],[3,4]]

我尝试使用 for 循环,但没有任何改变

【问题讨论】:

  • @sahasrara62 没有逗号分隔数字的字符串。
  • 请展示您尝试使用的 for 循环,以便我们解释您做错了什么,您会学得更好。

标签: python python-3.x string list integer


【解决方案1】:

对于所有子列表,如果你想要[['1,2'], ['3,4', '5,6']] > [[1, 2], [3, 4], [5, 6]]

就地更换:

此解决方案不会创建新列表。

old_list = [['1,2'], ['3,4']]

for elem in old_list:
    tmp = elem[0].split(',')
    elem.clear()
    elem.extend(int(n) for n in tmp)

print(old_list)  # [[1, 2], [3, 4]]

如果你想创建一个新列表:

old_list = [['1,2'], ['3,4']]

new_list = [
    [int(n) for n in tmp_2.split(",")]
    for tmp_1 in old_list
    for tmp_2 in tmp_1
]

print(new_list)  # [[1, 2], [3, 4]]

对于所有子列表,如果你想要[['1,2'], ['3,4', '5,6']] > [[1, 2], [3, 4, 5, 6]]

就地更换:

src = [['1,2'], ['3,4', '5,6']]

for elem in src:
    tmp = ','.join(elem).split(',')
    elem.clear()
    elem.extend(int(n) for n in tmp)

print(src)  # [[1, 2], [3, 4, 5, 6]]

如果你想创建一个新列表:

old_list = [['1,2'], ['3,4', '5,6']]

new_list = [
    [int(n) for n in ','.join(tmp_1).split(',')]
    for tmp_1 in old_list
]

print(new_list)  # [[1, 2], [3, 4, 5, 6]]

【讨论】:

    【解决方案2】:

    您可以尝试使用这样的综合列表。

    numbers = [
        list(map(int, expand_list2.split(",")))
        for expand_list1 in [['1,2'],['3,4']]
        for expand_list2 in expand_list1
    ]
    

    这可能有助于更好地解释上述内容https://www.w3schools.com/python/python_lists_comprehension.asp

    【讨论】:

    • 混合理解与列表中的映射对我来说是一种反模式。
    【解决方案3】:
    main_arr = [['1,2'],['3,4']]
    xx = [list(map(int, ','.join(sub_arr).split(',')))  for sub_arr in main_arr]
    print(xx)
    

    输出

    [[1, 2], [3, 4]]
    

    xx = list(map(lambda x: list(map(int, ','.join(x).split(','))), main_arr))
    

    for i, v in enumerate(main_arr):
         tmp = []
         for idx, val in enumerate(v):
                 tmp.extend([int(ij) for ij in val.split(',')])
         main_arr[i] = tmp
    

    【讨论】:

    • 混合理解与列表中的映射对我来说是一种反模式。
    • @DorianTurba 好的
    猜你喜欢
    • 2011-10-29
    • 1970-01-01
    • 2015-10-24
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2016-10-03
    相关资源
    最近更新 更多