[英]Replacing certain parts of a list in Python
I have a list of columns that represents months for different metrics.我有一个代表不同指标月份的列列表。 It was imported from a CSV.它是从 CSV 导入的。 There are two issues: (1) The months start with '22-' and (2) some months end with .1 , .2 etc.有两个问题:(1)月份以 '22-' 开头,(2)某些月份以 .1 、 .2 等结尾。
Here is the list:这是列表:
months = ['22-Apr', '22-May', '22-Apr.1', '22-Apr.2']
Tried using .replace
but I can't get it to remove only certain parts of the list尝试使用.replace
但我无法让它仅删除列表的某些部分
Among others, you could split
by '-'
and get the second part, then by '.'
其中,您可以用'-'
split
并得到第二部分,然后用'.'
分割。 and get the first part.并获得第一部分。 The latter will work even if there is no '.'
即使没有'.'
,后者也可以工作。 in the string.在字符串中。
>>> months = ['22-Apr', '22-May', '22-Apr.1', '22-Apr.2']
>>> [s.split("-")[1].split(".")[0] for s in months]
['Apr', 'May', 'Apr', 'Apr']
The [1]
means that this will work only if there is always a year-part present, but it does not matter if that has 2 or 4 digits. [1]
表示这仅在始终存在年份部分时才有效,但它是否具有 2 位或 4 位数字并不重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.