【问题标题】:Printing elements of a set in python [duplicate]在python中打印一组元素[重复]
【发布时间】:2018-08-30 06:16:41
【问题描述】:

我想连续打印集合的元素,所以写了如下代码:

s='dmfgd'
print(set(s))

但是,此代码显示输出为:

set(['m', 'd', 'g', 'f'])

但是,我想要这样的输出:

set(['d','m','f','g'])

任何帮助将不胜感激。

【问题讨论】:

  • list(dict(zip(s,s))) 应该可以解决您的问题
  • 或:print(sorted(set(s),key=s.index))

标签: python python-3.x set


【解决方案1】:

集合是无序的。如果您使用的是 Python 3.6+,则可以改为使用 dict 键列表来模拟有序集:

print(list(dict.fromkeys(s)))

这个输出:

['d', 'm', 'f', 'g']

【讨论】:

    【解决方案2】:

    Python setunordered 独特元素的集合

    试试:

    s='dmfgd'
    
    def removeDups(s):
        res = []
        for i in s:
            if i not in res:
                res.append(i)
        return res
    
    print(removeDups(s))
    

    输出:

    ['d', 'm', 'f', 'g']
    

    【讨论】:

      猜你喜欢
      • 2018-09-07
      • 1970-01-01
      • 2021-05-03
      • 2012-06-09
      • 2013-09-12
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      相关资源
      最近更新 更多