如何删除列表中数字周围的 ' ' 而不是字符串
How to delete ' ' around the numbers in my list but not the strings
所以我有一个包含字符串和整数的多维列表。但我需要按数字递增的顺序组织列表。问题是我的数字周围有 ' ',例如 '181'
。我不想从字符串中删除 ' ' 我只想从整数中删除它。
我的列表如下所示:
[['"Detective Pikachu"', '104', 'PG'], ['"The Secret Life of Pets 2"', '86', 'PG'], ['"Deadpool 2"', '119', 'R'], ['"Godzilla: King of the Monsters"', '132', 'PG-13
'], ['"Avengers: Endgame"', '181', 'PG-13'], ['"The Lion King(1994)"', '88', 'G']]
我只想要这个:
[['"Detective Pikachu"', 104, 'PG'], ['"The Secret Life of Pets 2"', 86, 'PG'], ['"Deadpool 2"', 119, 'R'], ['"Godzilla: King of the Monsters"', 132, 'PG-13
'], ['"Avengers: Endgame"', 181, 'PG-13'], ['"The Lion King(1994)"', 88, 'G']]
lists = [
['"Detective Pikachu"', '104', 'PG'],
['"The Secret Life of Pets 2"', '86', 'PG'],
['"Deadpool 2"', '119', 'R'],
['"Godzilla: King of the Monsters"', '132', 'PG-13'],
['"Avengers: Endgame"', '181', 'PG-13'],
['"The Lion King(1994)"', '88', 'G']
]
new_lists = [[int(item) if item.isdigit() else item for item in current_list] for current_list in lists]
整数周围有引号,因为它们实际上不是整数,它们是字符串——所以为了重申这个问题,你想在可能的情况下将所有字符串转换为整数,然后离开其余的字符串。
我认为 Python 中没有内置的 "maybe convert to int" 函数,所以我先做一个:
def maybe_convert_to_int(value: str) -> Union[int, str]
try:
return int(value)
except ValueError:
return value
然后将该函数映射到每个电影列表:
[movie.map(maybe_convert_to_int) for movie in movie_list]
所以我有一个包含字符串和整数的多维列表。但我需要按数字递增的顺序组织列表。问题是我的数字周围有 ' ',例如 '181'
。我不想从字符串中删除 ' ' 我只想从整数中删除它。
我的列表如下所示:
[['"Detective Pikachu"', '104', 'PG'], ['"The Secret Life of Pets 2"', '86', 'PG'], ['"Deadpool 2"', '119', 'R'], ['"Godzilla: King of the Monsters"', '132', 'PG-13
'], ['"Avengers: Endgame"', '181', 'PG-13'], ['"The Lion King(1994)"', '88', 'G']]
我只想要这个:
[['"Detective Pikachu"', 104, 'PG'], ['"The Secret Life of Pets 2"', 86, 'PG'], ['"Deadpool 2"', 119, 'R'], ['"Godzilla: King of the Monsters"', 132, 'PG-13
'], ['"Avengers: Endgame"', 181, 'PG-13'], ['"The Lion King(1994)"', 88, 'G']]
lists = [
['"Detective Pikachu"', '104', 'PG'],
['"The Secret Life of Pets 2"', '86', 'PG'],
['"Deadpool 2"', '119', 'R'],
['"Godzilla: King of the Monsters"', '132', 'PG-13'],
['"Avengers: Endgame"', '181', 'PG-13'],
['"The Lion King(1994)"', '88', 'G']
]
new_lists = [[int(item) if item.isdigit() else item for item in current_list] for current_list in lists]
整数周围有引号,因为它们实际上不是整数,它们是字符串——所以为了重申这个问题,你想在可能的情况下将所有字符串转换为整数,然后离开其余的字符串。
我认为 Python 中没有内置的 "maybe convert to int" 函数,所以我先做一个:
def maybe_convert_to_int(value: str) -> Union[int, str]
try:
return int(value)
except ValueError:
return value
然后将该函数映射到每个电影列表:
[movie.map(maybe_convert_to_int) for movie in movie_list]