Home > Enterprise >  Using .split() function within for loop referencing own parameter
Using .split() function within for loop referencing own parameter

Time:11-09

I am attempting to split a given string input in the format:

automobile car manufacturer maker children kids

and transform it into a list like so:

[['automobile','car'],['manufacturer', 'maker'], ['children', 'kids']]

The outer list basically should be separated by triple spaces, whereas the inner lists single spaces.

My code:

replacement_pairs = input().split('   ')
for p in replacement_pairs:
    p = p.split(' ')
print(replacement_pairs)

Returns this instead:

['automobile car', 'manufacturer maker', 'children kids']

CodePudding user response:

Use a simple list comprehension

data = 'automobile car   manufacturer maker   children kids'

replacement_pairs = [group.split(' ') for group in data.split('   ')]

print(replacement_pairs)

result:

[['automobile', 'car'], ['manufacturer', 'maker'], ['children', 'kids']]

In your current code:

    p = p.split(' ')

is a no-op since, p just gets assigned to the next element in the next iteration. You can't do any assigning to it. A simple fix would be to use a accumulating list instead of the assignment:

replacement_pairs = input().split('   ')
result = []
for p in replacement_pairs:
    result.append(p.split(' '))
print(result)

CodePudding user response:

Although list comprehension is more straightforward in this case, one way to do it without modifying your code too much would be:

replacement_pairs = input().split('   ')
for index, element in enumerate(replacement_pairs):
    replacement_pairs[index: index 1] = [element.split(' ')]
print(replacement_pairs)
  • Related