假设我有一个[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]
。
搜索时我找不到任何东西,但我觉得我错过了一些明显的东西。
感谢您的时间。
您可以使用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)
获得。
创建一个将保留唯一条目的新集。然后,您可以根据该集合进行过滤:
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]
。但是,如果要从列表中删除项目,使用索引可能会很棘手,所以我用while循环替换了for循环。另外,我建议您直接访问第一个数字,而不是获得切片。因此,您的代码看起来更像这样:
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
来支持构建新列表。与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])
首先将列表从低值到高值排序。检查数字的最高基数(因此对于350,这是100)并且如果之前没有发生此基数的倍数(即3),则将此值添加到新列表中
a_list = [210, 100, 250, 300, 405, 430, 500, 1850, 1875, 2120, 2150]
a_list.sort()
new_list = []
base = 1
pre_multiple = 0
for value in a_list:
while (value / base ) >= 10:
base *= 10
multiple = int(value/base)
if multiple != pre_multiple:
new_list.append(value)
pre_multiple = multiple
print(new_list)