【问题标题】:'str' object cannot be interpreted as an integer : Python error'str' 对象不能解释为整数:Python 错误
【发布时间】:2020-02-02 20:18:15
【问题描述】:

我正在编写一个函数,它将接收两个字符串列表作为参数。 我需要检查第二个列表中每个字符串在第一个列表中出现的次数并返回一个计数数组。我想从第一个数组中弹出找到的元素,以便在接下来的搜索中,我只需要移动较少的元素。但我在strings.pop(i) 上收到此错误。

def matchingStrings(strings, queries):
    a=[0 for i in range(len(queries))]
    j=0
    for i in queries :    
        while i in strings :
            a[j]=a[j]+1
            strings.pop(i)
        j=j+1
    return a

【问题讨论】:

  • 也请粘贴字符串和查询的数据。在不知道作为参数传递的输入类型的情况下无法对其进行调试。
  • @RafiqueMohammed 知道了!谢谢

标签: python python-3.x error-handling


【解决方案1】:

您会在docs 中找到:

s.pop([i]) - 在 i 检索项目并将其从 s

中删除

所以i 应该是一个索引,你给它一个字符串。您可能会更改为:

strings.pop(strings.index(i))

但这似乎是一种过度杀戮,而且您通过删除元素来提高效率的尝试也因为这条线:

while i in strings:

它可能不是明确的,但这条线每次都会循环列表。即使你让它更短,它也很多。

遍历列表仅一次的一种方法是使用Counter

from collections import Counter

strings = ["apple", "orange", "banana", "apple", "banana"]
queries = ["apple", "orange", "potato"]

c = Counter(strings)
res = [c[q] for q in queries]
print(res)

给予:

[2, 1, 0]

【讨论】:

    猜你喜欢
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    相关资源
    最近更新 更多