How do I combine elements from lists within a tuple under specific conditions?
If I have a tuple with lists like this:
ex_tuple = (['Dog', 'And', 'Cat'], ['World', 'Dog'], ['Hello', 'World', 'Cat'])
I am trying to combine the first two elements of the lists in the tuple only if the list has 3 elements.
I want my output to look like this:
(['Dog And', 'Cat'], ['World', 'Dog'], ['Hello World', 'Cat'])
My code looks like this so far
if any([(len(x) > 2) for x in ex_tuple]):
lst = [''.join(t).replace('', t[0] " " t[1]) for t in ex_tuple]
But, my output looks like this:
print(lst)
#['Dog AndDDog AndoDog AndgDog AndADog AndnDog AnddDog AndCDog AndaDog AndtDog And', 'World DogWWorld DogoWorld DogrWorld DoglWorld DogdWorld DogDWorld DogoWorld DoggWorld Dog', 'Hello WorldHHello WorldeHello WorldlHello WorldlHello WorldoHello WorldWHello WorldoHello WorldrHello WorldlHello WorlddHello WorldCHello WorldaHello WorldtHello World']
I'm struggling with how to go about fixing this issue, and I haven't been able to find any posts about this type of question. Would appreciate any help - thanks!
CodePudding user response:
You can use simple list comprehension with if ... else
:
ex_tuple = (["Dog", "And", "Cat"], ["World", "Dog"], ["Hello", "World", "Cat"])
lst = [[f"{l[0]} {l[1]}", l[2]] if len(l) == 3 else l for l in ex_tuple]
print(lst)
Prints:
[['Dog And', 'Cat'], ['World', 'Dog'], ['Hello World', 'Cat']]
CodePudding user response:
If we break the problem down into smaller pieces, it will be easer. First, let learn how to turn a 3-element list into a 2-element one:
def combine(my_list):
if len(my_list) == 3:
my_list = [my_list[0] " " my_list[1], my_list[2]]
return my_list
Next, we can combine that with list comprehension to achieve our goal:
new_tuple = tuple(combine(inner_list) for inner_list in ex_tuple)