如果第一个数字和长度相同,则从列表中删除数字

jhn*_*kly 4 python list-comprehension python-3.x

假设我有一个列表,[100, 210, 250, 300, 405, 430, 500, 1850, 1875, 2120, 2150] 我想删除任何以相同数字开头且长度相同的数字.结果应该是: [100, 210, 300, 405, 500, 1850, 2120]

到目前为止我所拥有的是:

for i in installed_tx_calc:
    if (len(str(i)) == 3) and (str(i)[:1] == str(i-1)[:1]):
        installed_tx_calc.remove(i)
    elif str(i)[:2] == str(i-1)[:2]:
        installed_tx_calc.remove(i)
Run Code Online (Sandbox Code Playgroud)

我有一个列表[862, 1930, 2496]和我的代码输出[1930].

搜索时我找不到任何东西,但我觉得我错过了一些明显的东西.

感谢您的时间.

Thi*_*lle 5

您可以使用itertools.groupby创建包含列表推导的新列表:

from itertools import groupby

numbers =  [100, 210, 250, 300, 405, 430, 500, 1850, 1875, 2120, 2150]

out = [next(group) for key, group in groupby(numbers, key=lambda n: (str(n)[0], len(str(n))))]

print(out)
# [100, 210, 300, 405, 500, 1850, 2120]
Run Code Online (Sandbox Code Playgroud)

我们使用元组(第一个数字,数字长度)进行分组,并保留每个组的第一个数字,这是我们得到的next(group).