私信  •  关注

Unnamed

Unnamed 最近回复了
3 年前
回复了 Unnamed 创建的主题 » 如何在python中提取和搜索字符串中的重复数字?

这段代码应该返回你想要的

string_list = [['1', '3', '4'], ['1', '3', '10']]

numbers = {}
for list in string_list:
    for item in list:

        if item not in numbers:
            numbers[item] = 1
        else:
            numbers[item] += 1

print(numbers)

这就回来了

{'1': 2, '3': 2, '4': 1, '10': 1}

这意味着有2个1,2个3,1个数字'4'和1个数字'10'。因此,存在重复。

如果您不想知道有多少个副本,可以运行:

string_list = [['1', '3', '4'], ['1', '3', '10']]

numbers = []
duplicates = False
for list in string_list:
    for item in list:

        if item not in numbers:
            numbers.append(item)
        else:
            duplicates = True
    if duplicates:
        break
    
print('There are duplicates' if duplicates else 'There are no duplicates')

这又回来了

There are duplicates

如果将字符串列表更改为['1',3',2',['5',8',10']],它将返回

There are no duplicates