[英]Finding if a reversed string has a match in a list of strings
我正在学习 Python,一个月后我正在努力解决以下问题:
冰淇淋店有一系列口味:
口味 = [“香蕉”,“巧克力”,“柠檬”,“开心果”,“覆盆子”,“草莓”,“香草”,]
他们想要建立一个包含 2 个球口味冰淇淋的所有替代品的列表。 口味不能重复:即。 Chocolate Banana 不能被列出,因为 Banana Chocolate 已经在列表中。 我必须打印清单。
这是我的代码:
result = []
sub_result = ""
for ice in FLAVORS:
for other_ice in FLAVORS:
if ice == other_ice:
continue
sub_result = ice + ", " + other_ice
if reversed(sub_result) in result:
continue
result.append(sub_result)
print ('\n'.join([item for item in result ])) '''
我无法让脚本绕过人情的反向迭代。
首先, reversed
反转可迭代对象。 它返回一个迭代器,而不是一个字符串! 而且您不想反转字符串,因为这会给您诸如'nomeL ,etalocohC'
类'nomeL ,etalocohC'
东西。
其次,利用这样一个事实,即您已经以相反的顺序知道您已经拥有哪些项目!
FLAVORS = [ "Banana", "Chocolate", "Lemon", "Pistachio", "Raspberry", "Strawberry", "Vanilla"]
result = []
for i, ice in enumerate(FLAVORS):
for other_ice in FLAVORS[i + 1:]:
result.append(f'{first_flavor} {second_flavor}')
print('\n'.join(result))
使用sub_result = ice + ", " + other_ice
使sub_result
成为一个字符串。 例如,对于Banana
and Chocolate
,您会得到'Banana, Chocolate'
。 你需要('Banana', 'Chocolate')
。
您需要改用tuple
或list
:
sub_result = tuple(reversed((ice, other_ice)))
注意转换为tuple
- 这是因为reversed
返回一个对象,而不是输入的反向。 该对象必须解释为所需的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.