我有一个字典,其中的数据看起来像:
imdb_data = {
'title': [
'The Shawshank Redemption',
'The Godfather',
'The Dark Knight',
'The Godfather: Part II']
'year': [
'(1994)',
'(1972)',
'(2008)',
'(1974)']
}
我宁愿从年份数据中删除括号,并让字典存储值:
imdb_data = {
'title': [
'The Shawshank Redemption',
'The Godfather',
'The Dark Knight',
'The Godfather: Part II']
'year': [
'1994',
'1972',
'2008',
'1974']
}
有没有一种方法可以用split或substrings来实现这一点?谢谢你的帮助!
imdb_data['year'] = [year[1:-1] for year in imdb_data['year']]
对您来说最好的是正则表达式
但如果你想要一个";快速而肮脏";方法:
for i, year in enumerate(imdb_data['year']):
imdb_data['year'][i] = year[1:-1]
您可以在此处使用strip,.strip('()')
:
>>> imdb_data = {
... 'title': [
... 'The Shawshank Redemption',
... 'The Godfather',
... 'The Dark Knight',
... 'The Godfather: Part II'],
... 'year': [
... '(1994)',
... '(1972)',
... '(2008)',
... '(1974)']
... }
>>>
>>> cleaned_years = []
>>> for year in imdb_data['year']:
... cleaned_years.append(year.strip('()'))
...
>>> imdb_data['year'] = cleaned_years
>>> print(imdb_data)
{'title': [
'The Shawshank Redemption',
'The Godfather',
'The Dark Knight',
'The Godfather: Part II'
],
'year': ['1994', '1972', '2008', '1974']}
或者,如果你想在列表理解中做到这一点,你可以做:
imdb_data['year'] = [year.strip('()') for year in imdb_data['year']]
有类似的函数只对字符串的前缀或后缀进行剥离,它们分别是.lstrip()
和.rstrip()
。
为什么不使用year[1:-1]
,如果某些值没有括号,请考虑
>>> year = '(1999)'
>>> year[1:-1]
'1999'
>>> year = '1999'
>>> year[1:-1]
'99'
而对于.strip('()')
,我们有
year = '1999'
year.strip('()') # '1999'
您只想删除存在的括号字符,而不是所有的前导和尾随字符。
在Python 3.10+上,您可以使用新的字符串方法来删除前缀和后缀:
imdb_data['year']=[e.removeprefix('(').removesuffix(')') for e in imdb_data['year']]
>>> imdb_data['year']
['1994', '1972', '2008', '1974']