如何查找列表中唯一单词的数量

时间:2013-04-11 00:38:40

标签: python list

例如:

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

2 个答案:

答案 0 :(得分:4)

字符串“join”方法在这里可能对您有用,但它不会为您提供您想要的答案。要将列表中的元素与“无”联系起来:

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])是另一回事。

答案 1 :(得分:1)

您是否有关于如何组合列表中元素的定义?

所以,假设你有你的例子

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']