-7

例如:

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

2 回答 2

4

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

于 2013-04-11T00:45:07.253 回答
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']

于 2013-04-11T00:56:09.387 回答