【发布时间】:2022-01-15 03:03:58
【问题描述】:
所以我在一些 Stack Overflow 用户的帮助下编写了这段代码......
它试图分析我的元组l 并查看该元组中的x 是否是它们的两对元素中的第一个字符
这是我的代码,
def two_pairs(l):
d = {}
for i, x in enumerate(l):
d.setdefault(x[0],[]).append(i)
for v in d.values():
if len(v) > 2:
return False
elif len(v) == 2:
if v[1] - v[0] == 1:
continue
else:
return False
else:
continue
return True
但是,这仅在输入是列表时才有效......就像
['AS', 'AD', 'CC', 'CH', 'CS'] returns False because there are 3 C and 2 , but there are supposed to be 2 of the same elements and one of a completely different element.
['AS', 'AD', 'SC', 'SH', 'CS'] returns True because there are 2 A, 2 S and one C.
['CS', 'CD', 'AC', 'AH', 'FS'] returns True because there are 2 C, 2 A and one F
['AS', 'CD', 'AC', 'CH', 'DS'] returns False because although there are two A, two C and one D, the A and C are not in order
但是,我希望我的代码当输入 h 是像 ('AS', 'CD', 'AC', 'CH', 'DS']) 这样的元组时能够工作,并且也返回 True 或 False..
我应该做些什么改变??
【问题讨论】:
-
请注意,您提供的元组 (
('AS', 'CD', 'AC', 'CH', 'DS'])) 中有一个额外的],因此它不是有效的元组。删除]可能会解决您的问题。
标签: python function boolean tuples