【问题标题】:The second list is being filled over and over. What is wrong with this python code?第二个清单被一遍又一遍地填写。这个 python 代码有什么问题?
【发布时间】:2020-05-22 22:09:28
【问题描述】:
def firstnonrepeatingchar(str1):
    list1=list(str1)
    list2=[]
    print(list1)
    for ch in list1:
        if ch not in list2:
            a=list1.count(ch)
            list2.append(a)
    print(list2)
    for x in list2:
        if(x==1):
            print(list1[x+2])



string1="aaabccc"
firstnonrepeatingchar(string1)

输出将 list2 作为 [3,3,3,1,3,3,3] 如何使其仅作为[3,1,3]?

【问题讨论】:

标签: python list append


【解决方案1】:

你得到这个[3,3,3,1,3,3,3]是因为你每次遇到这个角色时都在追加。

更好的方法是使用不允许重复并保留顺序的OrderedSet

from orderedset import OrderedSet

def firstnonrepeatingchar(str1):
    s = OrderedSet(str1)
    list2 = []
    for ch in s:
        list2.append(str1.count(ch))
    # or list2 = [str1.count(c) for c in s]
    print(list2)

string1="aaabccc"
firstnonrepeatingchar(string1)

代码中的错误:

if ch not in list2:

ch 永远不会出现在 list2 中,因为您永远不会将 ch 附加到 list2,而是附加计数。

修复您的代码:

def firstnonrepeatingchar(str1):
    list1 = []
    list2 = []
    for ch in str1:
        if ch not in list1:
            list1.append(ch)
            list2.append(str1.count(ch))
    print(list2)

虽然,我不推荐这个if ch not in list1:。它执行线性搜索。使用set 会更好地解决这个问题。

【讨论】:

    【解决方案2】:

    在第一个循环的 if 语句 if ch not in list2: 中,您正在检查当前 字符 是否在 list2 中。但是您将 counts 附加到该列表中。因此它永远不会通过该检查并为字符串/数组中的每个字符添加计数。我建议使用字典将字符及其计数存储在一起,因此 if 语句可以检查键(字符)是否存在,如果不存在则可以添加键及其计数。然后您应该能够找到第一个非重复字符(dic 中的第一个条目,计数为 1)。从 Python 3.6 开始,字典会记住插入的顺序,否则使用 OrderedDict。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 2017-02-19
      • 2015-08-04
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多