How can I solve the following problem? I want to delete parentheses and commas.
output = [("apple",), ("orange",), ("banana",)]
desired output = ["apple", "orange", "banana"]
CodePudding user response:
The items inside the list are tuples, simply iterate over it and get the items inside those tuples:
print([item for tup in output for item in tup])
This solution will work if your tuples are like [("apple","something-else"), ("orange",), ("banana",)]
Since in your situation there is only one item, you can do the following as well:
print([tup[0] for tup in output])
print([x for x, in output]) # Thanks @timgeb for mentioning in comments.
print([x for [x] in output])
CodePudding user response:
You can use chain
from itertools
import itertools
output = [("apple","apple"), ("orange","orange"), ("banana","banana")]
list(itertools.chain.from_iterable(output))
# ['apple', 'apple', 'orange', 'apple', 'banana', 'apple']
list(itertools.chain.from_iterable([("apple",), ("orange",), ("banana",)]))
# ['apple', 'orange', 'banana']
CodePudding user response:
output = [("apple",), ("orange",), ("banana",)]
# this bit is not needed, but is how I would go about
# learning about the structure of my data
>>> type(output) # find output type
list
>>> len(output) # find output length
3
>>>type(output[0]) # find output's element types
tuple
# this is how I would tackle the problem, assuming you
# want the data in a new list of just the strings
desiredOutput = [None] * len(output) # create empty list of same length
for i in range(0, len(output)): # loop over array
desiredOutput[i] = output[i][0] # [0] needed to access the first element of each tuple
>>> print(desiredOutput)
['apple', 'orange', 'banana']