问题描述
我有如下字符串列表:
my_list = ['abc','bcd','cde','def','efc']
如果想获得基于以下条件的输出:
- 字符串中的字符是连续的。例如:
"a"
、"b"
、"c"
、... - 列表中的后续元素也是连续的。例如:
"abc"
、"bcd"
、“cde”、... - 如果不满足上述任何条件,则
break
迭代
对于上面的例子,我需要输出像(以及元素索引):
0 abc
1 bcd
2 cde
4 efc
这是我试过的代码:
lst = ['abc','efc']
for idx,i in enumerate(lst):
if 'c' in i:
#here should be the other condition
print(idx,i)
但它只打印这些:
0 abc
1 bcd
2 cde
解决方法
您可以使用 ord()
找到字符的 unicode 代码。在下面的示例中,我使用 zip()
迭代字符串中的连续字符,然后匹配它们的 unicode 代码是连续的。然后我使用 all()
检查字符串的所有 unicode 代码是否连续:
my_list = ['abc','bcd','cde','def','efc']
for i,l in enumerate(my_list):
# check if element is first element in list
is_first = i == 0
# check if all the chars are continuous in string
is_continuous = all(ord(a)+1 == ord(b) for a,b in zip(l,l[1::]))
# Match the continuation order from previous index element.
# True,for 1st element
is_previous_match = is_first or ord(my_list[i-1][0])+1 == ord(l[0])
if is_continuous and is_previous_match:
print(i,l)
else:
break
将打印:
0 abc
1 bcd
2 cde
3 def
,
我想出了一个更简单的解决方案
my_list = ['lol','abc','cd e','efc','das da']
index = []
for i,l in enumerate(my_list):
if 'c' in l:
index.append(i)
for l in my_list[index[0]:]:
if 'c' in l:
print(l)
else:
break
abc
bcd
cd e