我对Python很新,我正在努力处理如何循环通过下面的问题的逻辑。所以,我有一个简单的列表,就像这样:python for循环逻辑来检查变量对
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
行,如果它,我想打印相应的url值(cat_list的第三列)。此外,如果在cat_list中找不到y
(但找到了x
),我想转到其对应的default
值,并再次在cat_list中输出相应的url值。
所以,上面的x
和y
,我想for循环输出cu d url name
。
但是,如果x
和y
人说,
x = "oxford university"
y = "cricket"
然后标识像for循环输出ou c url name
。
很抱歉,如果这是一个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
+1对你想达到什么的详细解释,但是-1对于你自己试图解决这个问题的尝试没有示范 – user4815162342
你可以尝试使用python字典。 http://docs.python.org/2/tutorial/datastructures.html#dictionaries –