【问题标题】:Comparing numpy.str to set that contains a single string将 numpy.str 与包含单个字符串的集合进行比较
【发布时间】:2020-09-17 21:02:58
【问题描述】:

我有以下字符串:

label1: 'Yes'(numpy 字符串)

label2: 'Yes'(仅包含单个字符串的集合)

当我尝试比较 label1 == label2 时出现错误,因为 label2 是一个集合,而不是一个字符串。

当我尝试比较 label1 == label2[0] 时出现错误,因为“集合不可下标”。

谁能帮我看看我错过了什么?

【问题讨论】:

  • numpy string 到底是什么意思?
  • 我使用 numpy genfromtext 函数将 csv 文件中的数据作为字符串值导入。当我调用 type(data) 它说 class numpy string.

标签: python string numpy string-comparison


【解决方案1】:

您缺少的是为您的功能选择了不合适的数据类型。 set 是一个无序集合;试图从中获取特定元素与set 概念不一致。

你有几个合理的选择。

if label1 in label2:

if label1 == list(label2)[0]:

【讨论】:

    【解决方案2】:

    集合是无序的数据结构,这意味着您可以在任何索引i 处获得值,这是因为只有有序结构可以被索引。在集合中,每次的顺序都是不同的,因此在特定元素上的索引值每次都会给出不同的结果,这是没有意义的(这就是不允许这样做的原因)

    如果你想让我让它工作,有很多方法。

    如果你有单一的价值:

    if label1 == list(label2)[0]:
        # Your code
    

    if label1 == label2.pop():
        # Your code
    

    如果您有多个值:

    if label1 == sorted(list(label2))[INDEX_OF_YOUR_VALUE]:
        # Your code
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      相关资源
      最近更新 更多