Home > OS >  Printing a string which is formed by taking each successive letter in the list of words based on the
Printing a string which is formed by taking each successive letter in the list of words based on the

Time:06-01

For example:

list = ['how', 'are', 'you', 'today']

output: hrua

printing the index0 of the first word and index1 of second word and so on...

please help!:(

CodePudding user response:

Using list comprehension and lambda function:

result = lambda list: [item[i] for i, item in enumerate(list)]

Or as a normal function

def bar(list):
    return [item[i] for i, item in enumerate(list)]
result = bar(....)

This returns the letters in a list. If you want to print them: l = ["how","are","you","today"] for index, value in enumerate(l): print(value[index])

You need to consider that this does not check for validity. If we look at the array:

["a", "b"]

This will return an error, as "b" only has index 0, and no index 1.

CodePudding user response:

The enumerate function is your friend docs here:

l = ["how","are","you","today"]
for index, value in enumerate(l):
    print(value[index])

CodePudding user response:

Try this:

l = ["how","are","you","today"]
"".join([x[i] for i, x in enumerate(l)])

# Output
# 'hrua'
  • Related