以这种方式从列表中提取数据时
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]
,但我认为这是一个非常尴尬的解决方案。
以这种方式从列表中提取数据时
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]
,但我认为这是一个非常尴尬的解决方案。
from itertools import chain
print tuple(chain(['a', 'b', 'c'], 'd', 'e'))
输出:
('a', 'b', 'c', 'd','e')
试试这个。
line = ['a', 'b', 'c', 'de']
tuple(line[0:3] + [line[3][:1]] + [line[3][1:]])
('a', 'b', 'c', 'd', 'e')
注意:我认为您的切片逻辑中有一些有趣的事情。如果 [2:] 返回任何字符,则 [:2] 必须返回 2 个字符。请提供您的输入行。
明显的答案:而不是你的第一行,做:
line[0:3] + [line[3][:2], line[3][2:]]
假设这line[0:3]
是一个列表,那是可行的。否则,您可能需要进行一些小的调整。
这个功能
def merge(seq):
merged = []
for s in seq:
for x in s:
merged.append(x)
return merged
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))
这应该适用于任何级别的嵌套