此代码对我来说一直很好:
a = '31'
b = ''
c = ''
d = ''
codes = [a, b, c, d]
set_one = ('07', '10', '17', '31')
set_two = ('01','02','03','04','05','06','08')
if any(s in test for test in codes for s in set_one):
result = '"ONE"'
elif any(s in test for test in codes for s in set_two):
result = '"TWO"'
else:
result = 'NULL'
print(result)
在此示例中,result
会打印回"ONE"
如果a,b,c或d设置为01
,则结果将打印回"TWO"
等等。
这个解决方案有一段时间了,因为只有一组代码可以在等式中表示,但我现在需要考虑一个和两个代表,(例如A = 07,B = 01) 。如果发生这种情况," 07"将由第一个if any
语句提取,并报告"ONE"
。
我需要构建功能,以便在整个codes
对象中表示两个组(例如codes = ['07','01','','']
),然后报告"THREE"
。
我不知道怎么做,虽然python不是我的强项...
这很有效。谢谢你们!
a = '01'
b = ''
c = ''
d = ''
codes = [a, b, c, d]
one_match = 0
two_match = 0
set_one = ('07', '10', '17', '31', 'CO', '12', '13', '25', '55', 'ZN', 'Z3', 'Z2')
set_two = ('01','02','03','04','05','06','08','11','14','15','16','18','19','20')
if any(s in test for test in codes for s in set_one):
one_match = 1
if any(s in test for test in codes for s in set_two):
two_match = 1
if one_match == 1 and two_match == 1:
result = "MIX"
elif one_match == 1:
result = "ONE ONLY"
elif two_match == 1:
result = "TWO ONLY"
else:
result = 'NULL'
print(result)
答案 0 :(得分:3)
不使用elif
进行测试并使用整数进行计数。
matches = 0
if any(s in test for test in codes for s in set_one):
matches += 1
if any(s in test for test in codes for s in set_two):
matches += 2
然后使用列表& matches
作为索引:
result = ["NULL","ONE","TWO","THREE"][matches]
答案 1 :(得分:1)
您可以像这样修改代码:
result = 'NULL'
if any(s in test for test in codes for s in set_one):
result = '"ONE"'
if any(s in test for test in codes for s in set_two):
result = '"TWO"'
print(result)
可能这不是最佳做法,但我相信它可以正常运作。