Reputation: 9268
When extracting data from a list this way
line[0:3], line[3][:2], line[3][2:]
I receive an array and two variables after it, as should be expected:
(['a', 'b', 'c'], 'd', 'e')
I need to manipulate the list so the end result is
('a', 'b', 'c', 'd', 'e')
How? Thank you.
P.S. Yes, I know that I can write down the first element as line[0], line[1], line[2]
, but I think that's a pretty awkward solution.
Upvotes: 5
Views: 10734
Reputation: 4578
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))
this should work for any level of nesting
Upvotes: 0
Reputation: 18008
from itertools import chain
print tuple(chain(['a', 'b', 'c'], 'd', 'e'))
Output:
('a', 'b', 'c', 'd','e')
Upvotes: 5
Reputation: 40340
Obvious answer: Instead of your first line, do:
line[0:3] + [line[3][:2], line[3][2:]]
That works assuming that line[0:3]
is a list. Otherwise, you may need to make some minor adjustments.
Upvotes: 1
Reputation: 26098
Try this.
line = ['a', 'b', 'c', 'de']
tuple(line[0:3] + [line[3][:1]] + [line[3][1:]])
('a', 'b', 'c', 'd', 'e')
NOTE: I think there is some funny business in your slicing logic. If [2:] returns any characters, [:2] must return 2 characters. Please provide your input line.
Upvotes: 1
Reputation: 1486
This function
def merge(seq):
merged = []
for s in seq:
for x in s:
merged.append(x)
return merged
source: http://www.testingreflections.com/node/view/4930
Upvotes: 0