有没有办法让两个名为list1和list2的列表能够在另一个列表中查找一个条目的位置。即。
list_one = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
list_two = ["h","e","l","l","o"]
我的目的是允许用户输入一个单词,然后程序将转换为与list_one中的字母条目对应的一组数字
所以如果用户确实输入了你好,那么计算机将返回85121215(作为条目的位置)
有可能这样做吗
答案 0 :(得分:8)
查找列表中项目的位置不是一个非常有效的操作。对于这种任务,dict是更好的数据结构。
>>> d = {k:v for v,k in enumerate(list_one)}
>>> print(*(d[k] for k in list_two))
8 5 12 12 15
如果您的list_one
始终只是字母表,则按字母顺序排列,使用内置函数ord
可能会更好,更简单。
答案 1 :(得分:2)
添加到@ wim的答案,可以通过简单的理解来完成。
>>> [list_one.index(x) for x in list_two]
[8, 5, 12, 12, 15]
答案 2 :(得分:0)
x.index(i)
返回列表i
的元素x
的位置
print("".join([str(list_one.index(i)) for i in list_two]))
85121215
答案 3 :(得分:0)
在列表中使用list_one = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
string = "hello"
positions = [list_one.index(c) for c in string]
print(positions)
# [8, 5, 12, 12, 15]
:
WebDriverWait
答案 4 :(得分:0)
你可以迭代思考清单:
DECLARE @query VARCHAR(max)
DECLARE @years VARCHAR(max)
SELECT @years = STUFF(( SELECT DISTINCT '],[' + ltrim(str(Years)) FROM
#Inquires ORDER BY '],[' + ltrim(str(Years)) desc FOR XML
PATH('')), 1, 2, '') + ']'
SET @query = 'INSERT INTO Table_Name SELECT *
FROM (SELECT ReportDate, Company, EventType, Years,Months#,
Months,Inquires FROM #Inquires
WHERE Company = ''Company_Name'')t PIVOT (SUM(Inquires)
FOR Years IN ('+@years+')) AS pvt ORDER BY Company, Months#'
EXECUTE (@query)
但是Wim的答案更优雅!