如何删除列表中数字周围的“”,而不是字符串

2024-06-01 14:46:51 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个包含字符串和int的多维列表。但我需要按数字的递增顺序来组织列表。问题是我的数字周围有'',例如'181'。我不想从字符串中删除“”,我只想从int中删除它

我的清单如下:

[['"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']]

Tags: ofthe字符串列表secret数字intpg
2条回答

整数周围有引号,因为它们实际上不是整数,它们是字符串,所以要重申这个问题,您需要在可能的情况下将所有字符串转换为整数,而不使用其他字符串

我认为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]
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]

相关问题 更多 >