![](/img/trans.png)
[英]Python - How do you replace the values of strings stored in a list with the string values from another list?
[英]How do you pick out certain values from a list based on their string values in Python?
我有一个超链接列表,其中包含三种类型的链接。 htm
, csv
和pdf
。 我只想挑出csv
那些。
该列表包含以下格式的字符串: csv/damlbmp/20160701damlbmp_zone_csv.zip
我当时想在字符串上运行一个for循环,只返回前三个字符串值等于csv
值,但是我不确定如何做到这一点。
如果您的列表称为links
:
[x for x in links if 'csv/' in x]
我会使用link.endswith('csv')
(或link.endswith('csv.zip')
),其中link
是包含该链接的字符串)
例如:
lst = ['csv/damlbmp/20160701damlbmp_zone_csv.zip',
'pdf/damlbmp/20160701damlbmp_zone_pdf.zip',
'html/damlbmp/20160701damlbmp_zone_html.zip',
'csv/damlbmp/20160801damlbmp_zone_csv.zip']
csv_files = [link for link in lst if link.endswith('csv.zip')]
你可以试试这个
import re
l=["www.h.com","abc.csv","test.pdf","another.csv"] #list of links
def MatchCSV(list):
matches=[]
for string in list:
m=re.findall('[^\.]*\.csv',string)
if(len(m)>0):
matches.append(m)
return matches
print(MatchCSV(l))
[['abc.csv'], ['another.csv']]
(endswith也是一个不错的选择)
这是一种方法:
lst = ['csv/damlbmp/20160701damlbmp_zone_csv.zip',
'pdf/damlbmp/20160701damlbmp_zone_pdf.zip',
'html/damlbmp/20160701damlbmp_zone_html.zip',
'csv/damlbmp/20160801damlbmp_zone_csv.zip']
[i for i in lst if i[:3]=='csv']
# ['csv/damlbmp/20160701damlbmp_zone_csv.zip',
# 'csv/damlbmp/20160801damlbmp_zone_csv.zip']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.