4

以这种方式从列表中提取数据时

line[0:3], line[3][:2], line[3][2:]

正如预期的那样,我收到一个数组和两个变量:

(['a', 'b', 'c'], 'd', 'e')

我需要操纵列表,所以最终结果是

('a', 'b', 'c', 'd', 'e')

如何?谢谢你。

PS 是的,我知道我可以将第一个元素写为line[0], line[1], line[2],但我认为这是一个非常尴尬的解决方案。

4

5 回答 5

4
from itertools import chain
print tuple(chain(['a', 'b', 'c'], 'd', 'e'))

输出:

('a', 'b', 'c', 'd','e')
于 2010-11-30T18:31:24.783 回答
1

试试这个。

line = ['a', 'b', 'c', 'de']
tuple(line[0:3] + [line[3][:1]] + [line[3][1:]])
('a', 'b', 'c', 'd', 'e')

注意:我认为您的切片逻辑中有一些有趣的事情。如果 [2:] 返回任何字符,则 [:2] 必须返回 2 个字符。请提供您的输入行。

于 2010-11-30T18:25:48.310 回答
1

明显的答案:而不是你的第一行,做:

line[0:3] + [line[3][:2], line[3][2:]]

假设这line[0:3]是一个列表,那是可行的。否则,您可能需要进行一些小的调整。

于 2010-11-30T18:29:09.807 回答
0

这个功能

def merge(seq):
    merged = []
    for s in seq:
        for x in s:
            merged.append(x)
    return merged 

来源:http ://www.testingreflections.com/node/view/4930

于 2010-11-30T18:15:03.577 回答
0
def is_iterable(i):
    return hasattr(i,'__iter__')

def iterative_flatten(List):
    for item in List:
        if is_iterable(item):
            for sub_item in iterative_flatten(item):
                yield sub_item
        else:
            yield item

def flatten_iterable(to_flatten):
    return tuple(iterative_flatten(to_flatten))

这应该适用于任何级别的嵌套

于 2010-11-30T19:10:23.233 回答