简体   繁体   English

将列表转换为由其元素组成的数字

[英]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.

相关问题 如何将列表转换为以逗号分隔的元素序列? - How to transform a list to a sequence of its comma-separated elements? 在python中返回由.split()元素组成的列表 - Returning a list in python that is composed of .split() elements 如何拆分由数字组成的列表? - How can I split a list composed of number? 选择由元素列表 pandas 组成的列的最后一个元素 - choosing the last element of a column composed by list of elements pandas 来自一个集合的列表理解,其元素是由两个元组组成的元组 - List comprehension from a set whose elements are tuples composed of two tuples 如何打印列表中元素数量最多的键? - How to print the key that has the most number of elements in its list? 子列表列表提供的子列表数量及其元素 - list of sub-lists provided number of sublists and its elements 如何将列表元素转换为百分比 - How to transform list elements into percentages 尝试形成一个列表,该列表的大小取自另一个列表中元素的数量,并将第一个列表的元素追加到新列表中 - Trying to form a list that takes its size from the number of elements in another list and appends the elements of the first list to the new list 如何找到列表的顺序,使其元素大于第二个列表中的相应元素。 我必须最大化这样的数字 - How to find an order of list such that its elements are greater than the corresponding elements in second list. I have to maximize such number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM