[英]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[] 的值 & 应该只获取索引引用,如下所示:
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-假设根据用户输入构造
S
后,它看起来像-
['a', 'a,b', 'd,e', ....]
And you would like it to look like-你希望它看起来像-
[[0], [0, 1], [3, 4]]
(indexes of said characters in U
) (
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-或者,如果您更喜欢 pythonic 方式-
P = [[U.index(c) for c in elem.split(',')] for elem in S]
# This will store the result in `P`
[[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(',')
注意:这显然取决于用户输入,但是如果您想允许像
a, b
以及a,b
这样a, b
用户输入a,b
只需使用S[i].split(',').strip()
而不是S[i].split(',')
Edit: It seems like OP wants the output to be-编辑:似乎 OP 希望输出是-
`['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]
[['U[0]'], ['U[0]', 'U[1]'], ['U[3]', 'U[4]']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.