如何删除列表中数字附近的“”而不是字符串

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

我的列表如下:

[['"Detective Pikachu"','104','PG'],['"The Secret Life of Pets 2"','86',['"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,86,119,132,181,88,'G']]
WMLwml5200 回答:如何删除列表中数字附近的“”而不是字符串

lists = [
    ['"Detective Pikachu"','104','PG'],['"The Secret Life of Pets 2"','86',['"Deadpool 2"','119','R'],['"Godzilla: King of the Monsters"','132','PG-13'],['"Avengers: Endgame"','181',['"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中没有内置的“也许转换为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]
本文链接:https://www.f2er.com/3163293.html

大家都在问