简体   繁体   English

如何在 Python 中按顺序获取列表元素的所有串联?

[英]How to get all concatenation of list elements in order in Python?

background背景

I have lists of numbers and symbols like:我有数字和符号列表,例如:

[1,':',2022,'.','01','.','01']

I would like to call a function like is_date(string) on every concatenation of the elements in order.我想在元素的每个串联上按顺序调用 function 之类的is_date(string)


minimal example最小的例子

Considering the simple example [1,2,3] as input, the expected list of concatenations should be: ['1','12','2','123','23','3']考虑将简单示例[1,2,3]作为输入,预期的串联列表应为: ['1','12','2','123','23','3']

I would like not to get '13' in the results我不想在结果中得到'13'

So afterwards I could call:所以之后我可以打电话:

for token in list_of_concatenation:
    if is_date(token):
        do something

You can use a double loop, slicing, and string concatenation:您可以使用双循环、切片和字符串连接:

l = [1, 2, 3]
l2 = [str(x) for x in l]
[''.join(l2[i:j+1]) for i in range(len(l2)) for j in range(i, len(l2))]

output: ['1', '12', '123', '2', '23', '3'] output: ['1', '12', '123', '2', '23', '3']

How about a nested for loop:嵌套的 for 循环怎么样:

sample = [1,':',2022,'.','01','.','01']
sample_str = [str(s) for s in sample]

for ix, i in enumerate(sample_str):
    for j in range(ix, len(sample_str)):
        print(''.join(sample_str[ix:j+1]))

output: output:

1
1:
1:2022
1:2022.
1:2022.01
1:2022.01.
1:2022.01.01
:
:2022
:2022.
:2022.01
:2022.01.
:2022.01.01
2022
2022.
2022.01
2022.01.
2022.01.01
.
.01
.01.
.01.01
01
01.
01.01
.
.01
01

You are not looking for the itertools.powerset() recipe because it ignores the "order":不是在寻找itertools.powerset() 配方,因为它忽略了“顺序”:

from itertools import  chain, combinations

# source:  https://docs.python.org/3/library/itertools.html
def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)

    # use  range(1, len(s)+1) to avoid empty result -> comment @mozway
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

d = [1,2,3]

print(list(powerset(d)))  

wich returns tuples as iterator (that I listified):至极返回元组作为迭代器(我列出):

[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

You can filter the result to remove the empty tuple and convert tuples to strings using您可以过滤结果以删除空元组并将元组转换为字符串使用

result = [''.join(map(str, tup)) for tup in powerset(d) if tup]

print(result)打印(结果)

to get要得到

['1', '2', '3', '12', '13', '23', '123']
  • for a not that efficient solution you could use that to filter down to what you really really want.对于一个效率不高的解决方案,您可以使用它来过滤您真正想要的东西。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM