简体   繁体   English

如何摆脱在python列表中包含列表的问题?

[英]How can I get rid of having lists inside of a list in python?

    def digit_sum(n):
        n = str(n)
        empty = [x.split() for x in n]
        print empty



    digit_sum(21)

This code will output: 此代码将输出:

     [['2'], ['1']]

What I need is to make it: 我需要做的是:

    [2, 1] 

so I can add the numbers in the list together. 因此我可以将列表中的数字加在一起。 How do I do that? 我怎么做?

I would just do (you don't need to .split it, just convert it to a string over which you can iterate): 我会做的(您不需要将它.split 。只需将其转换为可以迭代的字符串即可):

def digit_sum(n):
    empty = [int(d) for d in str(n)]
    print empty

Demo: 演示:

>>> digit_sum(21)
[2, 1]

You could then obviously add them together with the sum() function. 然后,您显然可以将它们与sum()函数一起添加。

Don't call split . 不要叫split Split tries to divide a string on whitespace (by default). Split尝试在空格上分割字符串(默认情况下)。 It will return a list of strings always (even if there were no splits to be made). 它将始终返回一个字符串列表(即使没有拆分也是如此)。

Since your loop is over a string, x will be a single character. 由于循环在字符串上,因此x将是单个字符。 That means you'll never have any whitespace to split on. 这意味着您永远不会有任何空白。

Just do [x for x in n] or list(n) . 只需执行[x for x in n]list(n)

Or if you want your digits as integers, rather than strings: [int(x) for x in n] or map(int, n) 或者,如果您希望数字不是整数,而是整数: [int(x) for x in n]map(int, n)

I believe if you 我相信如果你

firstlist.append(secondlist)

Python should print 1, 2. Posting from a Windows Phone, so I can't run the code, excuse my incompetence if this doesn't work. Python应该打印1、2。从Windows Phone发布,所以我不能运行代码,如果这样做不对不起,请原谅。

This works: 这有效:

def digit_sum(n):
  n = str(n)
  empty = [int(x) for x in n]
  print empty

digit_sum(21)

Output: 输出:

[2,1]

split returns a list. split返回一个列表。 for x in n will go over each character in the string and int(x) converts the character to an integer. for x in n将遍历字符串中的每个字符,并且int(x)将字符转换为整数。

>>> from itertools import chain
>>> x = [['2'], ['1']]
>>> map(int, chain(*x))
[2, 1]

If you want to completely flatten a list of lists, you need to check if its iterable. 如果要完全平整列表列表,则需要检查其是否可迭代。

To do this you can create a generator which returns a non-iterable item, or recursively calls itself if the item is iterable. 为此,您可以创建一个生成器,该生成器返回一个不可迭代的项目,如果该项目是可迭代的,则可以递归调用自身。

Then place each element of the generator in a list, and print it. 然后将生成器的每个元素放在列表中,并进行打印。

Warning!! 警告!!

This will crash with cycling lists ie l = []; l.append(l) 这将导致循环列表崩溃,即l = []; l.append(l) l = []; l.append(l)

def get_single_elements(item):
    if hasattr(item, '__iter__'):
        for child_item in item:
            for element in get_single_elements(child_item):
                yield element
    else:
        yield item

def print_flat(item):
    print [element for element in get_single_elements(item)]


>>> print_flat([[[0],[1]]])
[0, 1]
>>> print_flat([[[[[0,[1,2,[3,4]]]]],[[1]]]])
[0, 1, 2, 3, 4, 1]

Edit if you're sure you want to convert all items to ints, then write it like this 如果确定要将所有项目都转换为整数,则进行编辑 ,然后像这样编写

def print_flat(item):
        print [int(element) for element in get_single_elements(item)]

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

相关问题 如何使用 python 3 获得列表项列表中所有列表 [1] 的总和? - How can I get the sum of all list[1] inside of list of lists items using python 3? 如何摆脱列表内的列表而只在列表内包含数字? - How to get rid of lists inside of a list and only have numbers inside the list? 如何获得 python 列表的唯一嵌套列表? - How can I get the unique nested lists of a python list? 如何从 python 中的文件文件夹中获取列表列表? - How can I get a list of lists out a folder of files in python? 我如何基于python硒中超出范围的列表索引摆脱此错误 - How can I get rid of this error based on list index out of range in python selenium Python:为什么列表导入使用引号,如何避免/摆脱它们? - Python: Why does list import using quotation marks, how can I avoid this/get rid of them? 如何使用Python获取列表列表中最大列表的索引? - How do I get the index of the largest list inside a list of lists using Python? Python。 我如何 output 每个 for 循环实例作为嵌套列表,列表内的列表 - Python. How can I output each instance of a for loop as a nested list, lists inside a list 如何从python中的列表列表中获取n个最大列表 - How can I get n largest lists from a list of lists in python 如何摆脱列表中的 None 值? Python - How do I get rid of None values in list? Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM