[英]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. 然后将生成器的每个元素放在列表中,并进行打印。
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.