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.
PS 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.
from itertools import chain
print tuple(chain(['a', 'b', 'c'], 'd', 'e'))
Output:
('a', 'b', 'c', 'd','e')
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.
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.
This function
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))
this should work for any level of nesting
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.