sarvesh kumar
sarvesh kumar

Reputation: 213

Nested list Comparision with format string in python

l = ["Youtube", "Instagram", "Facebook"]

a = [
    [
        "{} {}".format(i[2 * j : 2 * j + 1], i[2 * j + 1 : 2 * j + 2])
        for j in range(len(i) // 2)
    ]
    for i in l
]
print(a)

This will return

[['Y o', 'u t', 'u b'], ['I n', 's t', 'a g', 'r a'], ['F a', 'c e', 'b o', 'o k']]

How the above list I can join first character space with the second character, Please tell if i missing anything in the inner array List.

Below is the output I want the odd space with even character

[['Yuu otb'], ['Isar ntga'], ['Fcbo aeok']]

Upvotes: 1

Views: 85

Answers (4)

yatu
yatu

Reputation: 88276

You could join slices of the strings as follows:

[[' '.join((s[:-1:2], s[1::2]))] for s in l]
# [['Yuu otb'], ['Isar ntga'], ['Fcbo aeok']]

Upvotes: 4

Celius Stingher
Celius Stingher

Reputation: 18377

I have combined zip and join

l = ["Youtube", "Instagram", "Facebook"]
a = [["{} {}".format(i[2 * j : 2 * j + 1], i[2 * j + 1 : 2 * j + 2])for j in range(len(i) // 2)]for i in l]
b = [[''.join(x) for x in zip(*i) if ''.join(x).replace(' ', '')] for i in a]
c = [' '.join(i) for i in b]
print(c)

Output:

['Yuu otb', 'Isar ntga', 'Fcbo aeok']

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49893

Sticking with the main structure of your original solution,

a = [
    [
        "{} {}".format("".join([i[2 * j : 2 * j + 1] for j in range(len(i) // 2)]),
            "".join([i[2 * j + 1 : 2 * j + 2] for j in range(len(i) // 2)]))
    ]
    for i in l
]

Upvotes: 0

James
James

Reputation: 36691

You don't actually need a double list comp for this. You can accomplish this by slicing up to the last even element and stepping by 2.

If you want them as single strings in a one-deep list:

[f'{x[:2*(len(x)//2):2]} {x[1:2*(len(x)//2):2]}' for x in l]
# returns:
['Yuu otb', 'Isar ntga', 'Fcbo aeok']

If you want them 2-deep:

[[f'{x[:2*(len(x)//2):2]} {x[1:2*(len(x)//2):2]}'] for x in l]
# returns:
[['Yuu otb'], ['Isar ntga'], ['Fcbo aeok']]

Upvotes: 1

Related Questions