简体   繁体   中英

How to replace list value with Index reference using python

I have a list:

U = ["a", "b", "c", "d", "e"]

With help of below code, i get below output as

 S = []        
 for i in range(0, 5):
    S.append(input("Source:- "))
    print((S[i]))

output:

S[0] = a 
S[1] = a,b 
S[2] = d,e
...

Now i need to replace the the values of S[] & should get theIndex reference only, as below one:

    S[0] =[ U[0] ] 
    S[1] =[ U[0] , U[1] ]
    S[2] =[ U[3] , U[4] ]

How to perform this, any clue pls.

Assuming after constructing S from user input, it looks like-

['a', 'a,b', 'd,e', ....]

And you would like it to look like-

[[0], [0, 1], [3, 4]]

(indexes of said characters in U )

You could do-

for i, elem in enumerate(S):
    S[i] = [U.index(c) for c in S[i].split(',')]

Or if you prefer the pythonic way-

P = [[U.index(c) for c in elem.split(',')] for elem in S]
# This will store the result in `P`

Output

[[0], [0, 1], [3, 4]]

Note: This is obviously dependent on user input, but if you want to permit user input like a, b as well as a,b simply use S[i].split(',').strip() instead of just S[i].split(',')

Edit: It seems like OP wants the output to be-

`['U[0]', ['U[0]', 'U[1]'], ['U[3]', 'U[4]']]`

I'm not sure what is the point of that at all, but here goes anyway-

P = [[f'U[{U.index(c)}]' for c in elem.split(',')] for elem in S]

Output

[['U[0]'], ['U[0]', 'U[1]'], ['U[3]', 'U[4]']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM