如果我想使用一个函数来识别字符串或变量中是否包含Class变量列表,我将如何识别与文本匹配的特定变量。
class numbersChecks:
number1 = "123"
number2 = "456"
number3 = "789"
numberCheck = [number1, number2, number3]
sample = "63D456DF1"
def main():
for i in numbersChecks.numberCheck:
if i in sample:
print(i)
if __name__ == '__main__':
main()
因此在此示例中,我可以取回456,但是如何取回实际的变量名,例如“ number2”
我实际上要处理的数据是非常长的十六进制字符串,因此,我试图避免将长字符串复制到单独的字典中,例如{number1:123, number2:456}
答案 0 :(得分:1)
您可以按索引或使用字典:
numbers_to_check = ['123', '456', '789']
for index, number in enumerate(numbers_to_check):
if number in sample:
print(index)
或
numbers_to_check = {'number1': '123', 'number2': '456', 'number3': '789'}
for key, number in numbers_to_check.items():
if number in sample:
print(key)
第三种方法是使用枚举:
from enum import Enum
class Numbers(Enum):
number1 = "123"
number2 = "456"
number3 = "789"
for number in Numbers:
if number.value in sample:
print(number.name)