Python 如果第一个数字和长度相同,则从列表中删除数字
假设我有一个Python 如果第一个数字和长度相同,则从列表中删除数字,python,python-3.x,list-comprehension,Python,Python 3.x,List Comprehension,假设我有一个[1002102503004054305001850187521202150] 我想删除所有以相同数字开头且长度相同的数字。 结果应该是:[10021030040550018502120] 到目前为止,我得到的是: 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
[1002102503004054305001850187521202150]
我想删除所有以相同数字开头且长度相同的数字。
结果应该是:[10021030040550018502120]
到目前为止,我得到的是:
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)
我有一个[86219302496]
列表,我的代码输出[1930]
搜索时我什么都找不到,但我觉得我遗漏了一些明显的东西
感谢您抽出时间。创建一个新的集合,以保留唯一的条目。然后,您可以根据该集合进行过滤:
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\u tx\u calc
中的字符串。但是,不能从字符串中减法。您真正想要的是使用i
作为索引,并通过以下方式进行访问:installed\u tx\u 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
您可以使用以下方法创建具有列表理解功能的新列表:
我们使用元组(第一个数字,数字的长度)进行分组,并保留每组的第一个数字,我们使用
next(group)
首先将列表从低值排序到高值。检查数字的最高基数(对于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)
您如何选择保留哪个号码?例如,删除210还是250有关系吗?我想先来先得,是否保证此列表已排序?是的,列表总是从最低到最高。我想保留较低的数字。太好了!非常感谢。
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])
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]
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)