gpt4 book ai didi

python - 创建并返回具有连续重复字母的所有国家/地区的元组

转载 作者:行者123 更新时间:2023-12-04 08:04:50 24 4
gpt4 key购买 nike

def get_doubled_letter_countries()
This function creates and returns a tuple of all the countries that have consecutive repeated letters. When called it returns that tuple, in alphabetical order by the doubled letters:
('morocco', 'greece', 'marshall islands', 'seychelles', 'cameroon', 'philippines', 'andorra', 'sierra leone', 'guinea-bissau', 'russia', 'saint kitts and nevis')
Notice they are in alphabetical order by the doubled letters: c, e, l, l, o, p, r, r, s, s, t

这是我的代码:

def get_doubled_letter_countries(double_letter_list):
""""
This function creates and returns a tuple of all the countries that have consecutive repeated letters.
When called it returns that tuple, in alphabetical order by the doubled letters:
"""
double_letter = re.compile(r'.*(.)\1.*', re.IGNORECASE)
double_letter_list = []
for countrie in countries:
for word in countrie.split(" "):
match = double_letter.match(word)
if match:
double_letter_list.sort()
double_letter_list.append(match.group())
print(tuple(double_letter_list))

它打印这个:(“安道尔”、“喀麦隆”、“希腊”、“几内亚比绍”、“基茨”、“编码(marshal)”、“摩洛哥”、“菲律宾”、“俄罗斯”、“塞舌尔”、“塞拉利昂”)

我需要它来打印:('摩洛哥', '希腊', '马绍尔群岛', '塞舌尔', '喀麦隆', '菲律宾', '安道尔', '塞拉利昂', '几内亚比绍', '俄罗斯', '圣基茨和尼维斯')

最佳答案

您的 regex 语句与您要实现的目标不匹配。

从捕获组的任一侧删除 .*

(.)\1

考虑到按连续字母排序的要求,我们可以将国家和匹配的正则表达式存储在元组列表中。然后我们可以使用 sorted()lambda 对匹配的元素进行排序。


countries= ('morocco', 'greece', 'marshall islands', 'seychelles', 'cameroon', 'philippines', 'andorra', 'sierra leone', 'guinea-bissau', 'russia', 'saint kitts and nevis')

def sorted_doubles(countries):

result = []
pattern = re.compile(r'(.)\1', re.IGNORECASE)

for c in countries:
match = pattern.search(c)
if match:
result.append((c, match.group(0)))

sorted_r = sorted(result, key=lambda x: x[1])

return tuple([country for country, _ in sorted_r])

print(sorted_doubles(countries))
#('morocco', 'greece', 'marshall islands', 'seychelles', 'cameroon', 'philippines', 'andorra', 'sierra leone', 'guinea-bissau', 'russia', 'saint kitts and nevis')

关于python - 创建并返回具有连续重复字母的所有国家/地区的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66272255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com