【问题标题】:How to find the numbers of unique words in a list [closed]如何查找列表中唯一单词的数量[关闭]
【发布时间】:2023-03-26 01:07:01
【问题描述】:

例如:

["apple", "banana", "apple", "mango"]

【问题讨论】:

  • 这里“组合”的定义是什么?
  • 字[0] = 例子[0];字[1] = 示例[1]+ 示例[2]; Word[2] = example[3]+ example[4] +example[5]+ example[6] + example[7];...我认为这只能用于 ["I","a", "m","h","a","p","p","y"] 变成 ["I","am","happy"]
  • 你怎么知道单词应该在列表中正确拆分的位置?
  • 回答您更新的问题:words = ["apple", "banana", "apple", "mango"]len(set(words))

标签: python list


【解决方案1】:

字符串“join”方法在这里可能对你有用,但它不会给你你想要的答案。用“nothing”连接列表的元素:

In [1]: "".join(["I","a","m","h","a","p","p","y"])
Out[1]: 'Iamhappy'

如果您的列表包含空格,您可以这样做:

In [2]: "".join(["I"," ","a","m"," ","h","a","p","p","y"])
Out[2]: 'I am happy'

后跟空格上的字符串“split”:

In [3]: 'I am happy'.split(" ")
Out[3]: ['I', 'am', 'happy']

但是解析字典单词的原始结果(Out[1])是另一回事。

【讨论】:

    【解决方案2】:

    你对如何组合列表中的元素有定义吗?

    所以,假设你的例子有

    x = ["I","a","m","h","a","p","p","y"]
    comb = [1, 2, 5]
    

    然后

    def combine(l, comb):
        x = []
    
        if sum(comb) == len(l):
            for n, i in enumerate(comb):
                d = sum(comb[:n])
                x.append(''.join(l[d : d + i]))
            return x
        return l
    

    combine(x, comb) 将返回['I', 'am', 'happy']

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 2012-09-09
      相关资源
      最近更新 更多