我对python很新,我正在努力解决如何循环以下问题的逻辑。所以,我有一个简单的列表,就像这样:
cat_list = [
["cambridge university", "cricket", "cu c url name"],
["cambridge university", "football", "cu f url name"],
["cambridge university", "golf", "cu g url name"],
["cambridge university", "default", "cu d url name"],
["oxford university", "cricket", "ou c url name"],
["oxford university", "football", "ou f url name"],
["oxford university", "golf", "ou g url name"],
["oxford university", "default", "ou d url name"],
["hertford university", "default", "hu d url name"],
]
然后,我有两个字符串x
和y
持有:
x = "cambridge university"
y = "nfl" # this can change
现在,我想检查(使用for循环)如果x
和y
匹配cat_list
行,如果匹配,我想打印相应的网址value(cat_list的第三列)。此外,如果在cat_list中找不到y
(但找到x
),我想转到相应的default
值并再次打印出cat_list中相应的url值。
因此,对于上面的x
和y
,我希望for循环输出cu d url name
。
但是,如果说x
和y
,
x = "oxford university"
y = "cricket"
然后我喜欢输出ou c url name
的for循环。
对不起,如果这是一个101问题 - 想想我只是非常困惑:(
修改的
所以,显然,人们可以运行qwwqwwq所描述的简单循环:
for item in cat_list:
if item[0] == x and item[1] == y:
print item[2]
for item in cat_list:
if item[0] == x and item[1] == 'default':
print item[2]
但是,x = "oxford university" y = "cricket"
if
上述y
都会得到满足 - 这不是我想要的。只有在未找到相应x
答案 0 :(得分:0)
使用数据结构,您需要循环两次,如果在第一次尝试时没有找到x和y匹配,那么查找默认值,如果找不到默认值,可能会提高例外..
def get_url(x,y,cat_list):
for item in cat_list:
if item[0] == x and item[1] == y:
return item[2]
for item in cat_list:
if item[0] == x and item[1] == 'default':
return item[2]
raise Exception("No default url found for {university}".format(university = x))
答案 1 :(得分:0)
正如其他答案所示,您可以对列表进行简单循环,以查看是否存在匹配值。处理默认值有点复杂,但如果您在浏览列表时看到它,则可以保存,如果到达循环结束则打印它。
default = None
for university, sport, url_name in cat_list:
if university == x:
if sport == y:
print url_name
break # stop looping
elif sport == 'default':
default = url_name
else: # triggered only if the loop reached the end without hitting a break statement
print default
如果您要多次查询同一个列表,可以使用字典来获得更好的性能。以下是如何从当前列表创建字典:
cat_dict = {(university, sport): url_name for (university, sport, url_name) in cat_list}
要查询给定的x
和y
:
if (x, y) in cat_dict:
print cat_dict[x, y]
else:
print cat_dict[x, 'default']
此版本平均每个查询需要O(1)
(常量)时间,而上面的循环为O(N)
。