Reputation: 31
I have a list of strings i will like to access and print its inner elements as shown below:
mylist = ['apple', 'balls', 'camera', 'dough', 'eleven']
specified_index = random.choices((range(len(mylist))), k=len(mylist))
print("specified_index =", specified_index)
merged_index = [mylist[tt] for tt in specified_index]
print("merged_index =", merged_index)
The result of merged_index keeps printing the words found at specified_index. Sample Output:
specified_index = [2, 3, 4, 0, 1]
merged_index = ['camera', 'dough', 'eleven', 'apple', 'balls']
What i want instead is to keep printing the corresponding letter of specified_index -not the whole words even if the list is shuffled. #For example: My preferred output == "mgeaa"
specified_index = [2, 3, 4, 0, 1]
merged_index = ['caMera', 'douGh', 'elevEn', 'Apple', 'bAlls']
Note::: I tried
import more_itertools as mit
merged_list = mit.random_product(mylist)
but it doesn't allow me to maintain same specified_index whenever mylist is shuffled #Other answers i found does not really solve this.
Upvotes: 0
Views: 44
Reputation: 22360
Assuming all the words in mylist
are longer than or equal to the length of mylist
a list comprehension could be used to achieve your desired result:
>>> import random
>>> mylist = ['apple', 'balls', 'camera', 'dough', 'eleven']
>>> specified_index = random.choices((range(len(mylist))), k=len(mylist))
>>> specified_index
[2, 3, 4, 0, 1]
>>> merged_index = [f'{mylist[i][:i]}{mylist[i][i].upper()}{mylist[i][i+1:]}' for i in specified_index]
>>> merged_index
['caMera', 'douGh', 'elevEn', 'Apple', 'bAlls']
>>> merged_word = ''.join(mylist[i][i] for i in specified_index)
>>> merged_word
'mgeaa'
As an aside, since python employs duck typing using Hungarian notation for variables in Python (mylist
) is kinda sus ngl... consider using words
or something else that doesn't reference the type next time fr fr.
Upvotes: 1
Reputation: 7903
You need to access each element in mylist at the same time as iteration through specified_index
. You can do that with zip
. Then use ''.join
to get the desired result.
mylist = ['apple', 'balls', 'camera', 'dough', 'eleven']
specified_index = random.choices((range(len(mylist))), k=len(mylist))
print("specified_index =", specified_index)
merged_index = ''.join([elem[tt] for elem, tt in zip(mylist, specified_index)])
print("merged_index =", merged_index)
specified_index = [2, 0, 0, 2, 4]
merged_index = pbcue
Upvotes: 1