错误列表索引必须是整数或切片,而不是str [英] error list indices must be integers or slices, not str
问题描述
根据标题,帮助我解决错误. 我试图根据在'rv'变量中的country_name打印countryCode. country_found是国家列表中具有相同值的数据列表, 然后我尝试检索countryCode,然后出现错误
Based on the title, help me solve the error. i've tried to print the countryCode based on country_name which is in 'rv' variable. country_found is list of data that have the same value on countries list, and then i try to retrieve countryCode and there i got the error
rv = "Indonesia"
country_lower = rv.lower()
countries = {
"DATA": {
"data": [{
"countryId": "26",
"countryCode": "AU",
"name": "Australia"
}, {
"countryId": "17",
"countryCode": "ID",
"name": "Indonesia"
}]
}
}
def take_first(predicate, iterable):
for element in iterable:
if predicate(element):
yield element
break
country_found = list(
take_first(
lambda e: e['name'].lower() == country_lower,
countries['DATA']['data']
)
)
default_country_code = 'US'
country_code = (
country_found['countryCode']
if country_found
else default_country_code
)
print (country_code)
推荐答案
country_found
是一个列表,但是您正在尝试通过字符串索引获取项目:
country_found
is a list, but you are trying to get an item by a string index:
country_found['countryCode']
您可能打算获得比赛的第一个结果:
You've probably meant to get the first result of a match:
country_code = country_found[0]['countryCode'] if country_found else default_country_code
但是,您实际上是否需要将结果作为列表,如果只使用 next()
:
But, do you actually need to have the result as a list, what if you would just use next()
:
result = take_first(lambda e: e['name'].lower() == country_lower,
countries['DATA']['data'])
try:
country_code = next(result)['countryCode']
except StopIteration:
country_code = default_country_code
这篇关于错误列表索引必须是整数或切片,而不是str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!