[英]how to extract specific items from the list with numbers and words in python?
i have a huge list of data in the given format.i need to extract all the data with year 2000.i get this error invalid literal for int() with base 10:'year'我有给定格式的大量数据列表。我需要提取 2000 年的所有数据。我得到这个错误 int() 的无效文字,基数为 10:'year'
['title','country','year','val',]
['bm','china','1987','2200']
['bm','japan','2000','1600']
['bm','germany','2000','70']
#it doesnt seem to work
new=[]
for i in list:
if i[2]==2000:
new.append(int(i))
You can try你可以试试
new = [i for i in list[1:] if '2000' == i[2]]
'list' is a keyword in python. 'list' 是 python 中的关键字。 Its best practice to avoid using it in code.避免在代码中使用它的最佳实践。
The reason you are getting literal error, is because your code is trying to convert String 'Year' to int.您收到文字错误的原因是因为您的代码正在尝试将 String 'Year' 转换为 int。 Remove the 1st list ( headers ) from the conversion.从转换中删除第一个列表( headers )。
1st, you should NOT be naming your variable as list
, because list
is a built-in data type of Python.第一,您不应该将变量命名为list
,因为list
是 Python 的内置数据类型。 You should NOT name your variables and functions the same as the built-in types and functions.您不应将变量和函数命名为与内置类型和函数相同的名称。 Use something else, ex.使用其他东西,例如。 mylist
.我的mylist
。
2nd, it's probably not working because you are including the list ['title', 'country', 'year', 'val',]
in the loop, and i[2]
will be "year"
and when your tried to cast "year"
(a string) to an int, it raised the error.第二,它可能不起作用,因为您在循环中包含列表['title', 'country', 'year', 'val',]
,并且i[2]
将是"year"
并且当您尝试投射时"year"
(一个字符串)到一个整数,它引发了错误。
One option is to skip the 1st list that looks like a header.一种选择是跳过第一个看起来像 header 的列表。
mylist = [
['title','country','year','val',],
['bm','china','1987','2200'],
['bm','japan','2000','1600'],
['bm','germany','2000','70']
]
new=[]
for i in mylist[1:]:
year = int(i[2])
if year==2000:
new.append(i)
print(new)
# [['bm', 'japan', '2000', '1600'], ['bm', 'germany', '2000', '70']]
Another option if you don't know whether the i[2]
will be a valid integer value, is to try
to cast it and then just skip it if it fails:如果您不知道i[2]
是否是有效的 integer 值,另一种选择是try
转换它,然后如果失败则跳过它:
mylist = [
['title','country','year','val',],
['bm','china','1987','2200'],
['bm','japan','2000','1600'],
['bm','germany','2000','70']
]
new=[]
for i in mylist:
try:
year = int(i[2])
except ValueError:
continue
if year==2000:
new.append(i)
print(new)
# [['bm', 'japan', '2000', '1600'], ['bm', 'germany', '2000', '70']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.