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

2024-03-29 08:54:02 发布

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

假设我有一个[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)

我有一个[862, 1930, 2496]列表和我的代码输出[1930]。你知道吗

我找的时候什么都找不到,但我觉得我遗漏了一些明显的东西。你知道吗

谢谢你抽出时间。你知道吗


Tags: installedand代码in列表forlenif
3条回答

创建一个将保留唯一条目的新集合。然后,您可以根据该集合进行过滤:

unique = set()
mylist = [100, 210, 250, 300, 405, 430, 500, 1850, 1875, 2120, 2150]
newlist = []

for num in mylist:
    num_str = str(num)
    length = len(num_str)
    first_digit = num_str[0]
    if (length, first_digit) in unique:
        continue
    newlist.append(num)
    unique.add((length, first_digit))

>>> newlist
[100, 210, 300, 405, 500, 1850, 2120]

目前,您正在使用变量i作为installed_tx_calc中的字符串。但是,不能从字符串中减去。您真正想要的是使用i作为索引,并以这种方式进行访问:installed_tx_calc[i]。但是,如果要从列表中删除项,则使用索引可能会很棘手,因此我将for循环替换为while循环。另外,我建议您直接访问第一个数字,而不是获取切片。因此,您的代码看起来更像这样:

i = 1
while i < len(installed_tx_calc):
    if len(str(installed_tx_calc[i]) == 3 and str(installed_tx_calc[i])[0] == str(installed_tx_calc[i-1])[0]:
        installed_tx_calc.remove(i)
        continue
    elif str(installed_tx_calc[i])[0] == str(installed_tx_calc[i-1])[0]:
        installed_tx_calc.remove(i)
        continue
    i += 1

请记住,如果您有更多的长度不等于3或4的数字,这将打破。更具扩展性的解决方案是:

i = 1
while i < len(installed_tx_calc):
    if len(str(installed_tx_calc[i])) == len(str(installed_tx_calc[i-1])) and str(installed_tx_calc[i])[0] == str(installed_tx_calc[i-1])[0]:
        installed_tx_calc.remove(i)
        continue
    i += 1

最后一个优化是避免使用remove来构建一个新的列表。^与append相比,{}可能是一个相当慢的操作,因此以下操作将比前两种解决方案更快:

new_itc = []
for i in range(1, len(installed_tx_calc):
    if not (len(str(installed_tx_calc[i])) == len(str(installed_tx_calc[i-1])) and str(installed_tx_calc[i])[0] == str(installed_tx_calc[i-1])[0]):
        new_itc.append(installed_tx_calc[i])

您可以使用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]

我们使用元组(第一个数字,数字的长度)分组,并保留每个组的第一个数字,这是通过next(group)得到的。你知道吗

相关问题 更多 >