有人能帮我解决这个超级新手蟒蛇的问题吗。我试过搜索好几次。
,这是我所提供的列表:
fruits = [{"key":"Red","value":"Apple"},
{"key":"Yellow-0","value":"Mango"},
{"key":"Green","value":"Banana"}]在某些情况下也可能是公正的:
fruits = [{"key":"Yellow-0","value":"Mango"}]问题陈述
我想迭代这个列表,只在有Yellow-0或Yellow-1等的情况下匹配,直到Yellow-9
我的代码
import re
fruits = [{"key":"Red","value":"Apple"},
{"key":"Yellow-0","value":"Mango"},
{"key":"Green","value":"Banana"}]
keyword = r"Yellow-\d"
for key in fruits:
if keyword:
print(fruits)我的输出
[{'key': 'Red', 'value': 'Apple'}, {'key': 'Yellow-0', 'value': 'Mango'}, {'key': 'Green', 'value': 'Banana'}]
[{'key': 'Red', 'value': 'Apple'}, {'key': 'Yellow-0', 'value': 'Mango'}, {'key': 'Green', 'value': 'Banana'}]
[{'key': 'Red', 'value': 'Apple'}, {'key': 'Yellow-0', 'value': 'Mango'}, {'key': 'Green', 'value': 'Banana'}]我想要的输出是匹配黄-0并返回true,因为这将是函数的一部分。
Yellow-0发布于 2022-09-22 21:28:38
我还没有在Python中使用正则表达式,但这可能会奏效:
pattern = re.compile("Yellow-\d")
for fruit in fruits:
if pattern.match(fruit['value']):
print(fruit['value'])如果它在钥匙里..。
pattern = re.compile("Yellow-\d")
for fruit in fruits:
match = fruit['value'] if pattern.match(fruit['value']) else False
match = fruit['key'] if not match and pattern.match(fruit['key']) else False
if match:
print(match)使用三元运算符,var = [value_1] if [condition] else [value_2]会将事情组织起来,这样就不会有嵌套的if/ you语句来干扰代码。
发布于 2022-09-22 21:18:55
为什么不使用它就导入re?
你有一份字典列表:
for fruit in fruits:
for key, value in fruit.items():
if value == <your string>:
print(value) 发布于 2022-09-22 22:01:40
您没有正确地实现您的列表,这里有一个简单的解决方案,不需要导入某些库。希望能帮上忙
#the name 'key' and 'value' are hundled by the dictionary brakets "{}" for that
you do not need to write them
fruits = [{ "Apple": "Red"}, {"Mango": "Yellow-0"}, {"Banana": "Green"}]
#this is the string value you search for
DesiredString = "Yellow-0"
#Nested for loop to iterate over two stage [the fruit stage, and the key_value
stage
for fruit in fruits :
for key, value in fruit.items() :
if value == DesiredString :
print(key)https://stackoverflow.com/questions/73820672
复制相似问题