社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

基本Python练习:给定一个整数列表,如果有重复,则放置一个“*”

ILoveMath • 5 年前 • 1548 次点击  

问题:用python编写一个代码,该代码执行以下操作:给定一个列表作为输入,输出将是相同的列表,但如果有重复,则将用 '*'

例如,如果输入是 [1,2,3,4,4,5,4] ,则输出为 [1,2,3,'*', '*', 5 , '*']

尝试:我的第一个方法是

c = [1,2,3,4,4,4,6,7]
d = [c[0]]
for i in range(len(c)-1):
    if c[i+1]==c[i]:
        c[i+1]= '*'

    d.append(c[i+1])

print(d)

但是,很明显,这不起作用。现在,我正在想办法解决这个问题。我是python新手,所以我想弄清楚。在这里可以循环一会儿吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55371
 
1548 次点击  
文章 [ 5 ]  |  最新文章 5 年前
Rabin Poudyal
Reply   •   1 楼
Rabin Poudyal    5 年前

c = [1,2,3,4,4,4,6,7]
from collections import Counter

count = Counter(c)
items = []
for k,v in count.items():
  if v > 1:
    for item in range(v):
      items.append('*')
  else:
    items.append(k)
print(items)
Venkataraman R
Reply   •   2 楼
Venkataraman R    5 年前

您可以在python中尝试下面的方法。

>>> c = [1,2,3,4,4,4,6,7]
>>> new_c = []
>>> for index,value in enumerate(c):
    if value in new_c:
        new_c.append('x')
    else:
        new_c.append(value)

>>> new_c
[1, 2, 3, 4, 'x', 'x', 6, 7]

同意@wjandrea的评论,我们不需要枚举,因为我们没有使用索引。

我们可以简化如下:

>>> new_c = []
>>> for value in c:
    if value in new_c:
        new_c.append('x')
    else:
        new_c.append(value)
>>> new_c
[1, 2, 3, 4, 'x', 'x', 6, 7]
AkshayNevrekar
Reply   •   3 楼
AkshayNevrekar    5 年前

你需要:

c = [1,2,3,4,4,4,6,7,6]

dup_c = []
for idx,i in enumerate(c):
    if i in dup_c:
        c[idx] = "*"
    else:
        dup_c.append(i)

print(c)

输出:

[1, 2, 3, 4, '*', '*', 6, 7, '*']
Keyur Potdar
Reply   •   4 楼
Keyur Potdar    5 年前

你可以用 collections.Counter 计算每个数字的出现次数,然后用 *

>>> from collections import Counter
>>> c = [1, 2, 3, 4, 4, 5, 4]
>>> count = Counter(c)
>>> d = [x if count[x] == 1 else '*' for x in c]
>>> d
[1, 2, 3, '*', '*', 5, '*']
wjandrea
Reply   •   5 楼
wjandrea    5 年前

如果只需要替换连续的重复(例如。 [1, 1] [1, 1, 0, 1] 但不是 [1, 0, 1] ),你可以使用 itertools.groupby

from itertools import groupby

def replace_repeats_with_stars(list_in):
    """
    >>> replace_repeats_with_stars([1, 1])
    ['*', '*']
    >>> replace_repeats_with_stars([1, 1, 0, 1])
    ['*', '*', 0, '*']
    >>> replace_repeats_with_stars([1, 0, 1])
    [1, 0, 1]
    """
    repeats = {k for k, g in groupby(list_in) if len(list(g)) > 1}
    return ['*' if x in repeats else x for x in list_in]