[英]Transform a list to a number composed of its elements
I'd like to convert a list, for example [1,0,1,0]
to the number 1010
(type int
). 我想将一个列表,例如
[1,0,1,0]
转换为数字1010
(类型为int
)。 Moreover, I'd like to do it within a function, so not using return
. 此外,我想在一个函数中执行此操作,因此不要使用
return
。 Is it possible and how can I do it? 有可能吗,我该怎么办?
def convert_list_of_ints_to_int( lst ):
return reduce(lambda x, y: x*10 + y, lst)
I would recommend 我会推荐
def concat_list(inlist):
return sum(10**pwr*elem for pwr, elem in enumerate(inlist[::-1]))
in verbose form 冗长的形式
def concat_list(inlist):
res = inlist[0]
for elem in inlist[1:]:
res=res*10+elem
return res
IMHO, @JonClements' comment is clearly the most pythonic answer: 恕我直言,@ JonClements的评论显然是最Python的答案:
int(''.join(map(str, some_list)))
Though I'd use a generator-comprehension, which is generally preferable over map
, and is more readable: 尽管我将使用生成器理解,它通常比
map
更可取,并且更具可读性:
int(''.join( str(num) for num in some_list ))
Here is another solution, using numpy
. 这是另一个解决方案,使用
numpy
。 I don't claim it is better than any of the other answers, but I find it cool nevertheless. 我并不是说它比其他任何答案都要好 ,但是我仍然觉得它很酷。
a = [1,0,1,0]
( a * 10**numpy.arange(len(a))[::-1] ).sum()
=> 1010
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.