first = "q w e r t y u i o p"
second = "a s d f g h j k l"
third = "z x c v b n m"
first_1 = first.split()
First_1 = first.upper().split()
second_1 = second.split()
Second_1 = second.upper().split()
third_1 = third.split()
Third_1 = third.upper().split()
words = ["Twitter", "TOTO", "FishC", "Python", "ASL"]
result = []
a = 0
b = 0
c = 0
for each in words:
print(each)
for i in each:
if i.startswith(tuple(first_1)) or i.startswith(tuple(First_1)):
a = 1
continue
elif i.startswith(tuple(second_1)) or i.startswith(tuple(Second_1)):
b = 1
continue
elif i.startswith(tuple(third_1)) or i.startswith(tuple(Third_1)):
c = 1
continue
if a == 1 and b == 0 and c == 0:
result.append(each)
elif a == 0 and b == 1 and c == 0:
result.append(each)
elif a == 0 and b == 0 and c == 1:
result.append(each)
else:
continue
print("输出",result)
求问各位大佬:
1.为什么这个结果里没有ASL 按理说ASL也是满足条件的 我实在找不出来错误
本帖最后由 isdkz 于 2022-2-28 21:49 编辑
你的思路没有问题,不过有一些建议:
第一:没必要把大写和小写分开,你可以先用 lower() 把大写变成小写
第二:i 只是一个字符,你直接用 in 即可,没必要用 startswith
第三:对于这种判断有一个更好用的函数:
all: 接收一个可迭代对象,可迭代对象全为 True 时返回True
小技巧:python给函数传生成器生成式时,可以把函数调用的括号跟生成器生成式的括号共用
第四:循环体的最后本来就要进入下一次循环了,没必要加 continue
故对你的代码修改如下:first = "qwertyuiop"
second = "asdfghjkl"
third = "zxcvbnm"
words = ["Twitter", "TOTO", "FishC", "Python", "ASL"]
result = []
for each in words:
print(each)
if all(i.lower() in first for i in each):
result.append(each)
elif all(i.lower() in second for i in each):
result.append(each)
elif all(i.lower() in third for i in each):
result.append(each)
print("输出",result)
|