Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用字符串中的每个字符表示列表中每个整数的结果?_Python_List - Fatal编程技术网

Python 如何使用字符串中的每个字符表示列表中每个整数的结果?

Python 如何使用字符串中的每个字符表示列表中每个整数的结果?,python,list,Python,List,在python中,我有这样一个字符串:AABBAA。字符串始终为6个字符。我还有一个整数列表,如:[2,5,4,6,0,9]。它们始终是单个整数(0-9),并且始终是6个整数(以匹配字符串)。字符“A”表示使用列表、A_列表,对于整数列表中与其匹配的数字(以索引的形式),它使用该数字对A_列表进行索引。字符“B”也一样。因此,在上面的示例中,您将得到: 清单[2] 清单[5] B_列表[4] B_列表[6] A_列表[0] 清单[9] 我曾经尝试过制作一本字典,它有a和B键,并将数字填入匹配

在python中,我有这样一个字符串:AABBAA。字符串始终为6个字符。我还有一个整数列表,如:[2,5,4,6,0,9]。它们始终是单个整数(0-9),并且始终是6个整数(以匹配字符串)。字符“A”表示使用列表、A_列表,对于整数列表中与其匹配的数字(以索引的形式),它使用该数字对A_列表进行索引。字符“B”也一样。因此,在上面的示例中,您将得到:

  • 清单[2]
  • 清单[5]
  • B_列表[4]
  • B_列表[6]
  • A_列表[0]
  • 清单[9]

我曾经尝试过制作一本字典,它有a和B键,并将数字填入匹配的值中,但我很难理解它。谢谢。

您需要将输入列表映射到易于访问的标识符。一种方法是使用字典。然后将列表理解与
zip
一起使用:

d = {'A': list(range(10)),
     'B': list(range(10, 20))}

lists = 'AABBAA'
keys = [2,5,4,6,0,9]

res = [d[lst][key] for lst, key in zip(lists, keys)]

print(res)

[2, 5, 14, 16, 0, 9]

让我们制作一个字典,其中键是字符串中的不同字母,在我们的例子中,我们将有键
“a”
“B”
,这两个键都有它们表示为其值的列表

mappings = {"A":A_List, "B":B_List}
为了从列表中获得正确的值,我们需要循环遍历字符串以找出我们正在使用的列表,以及整数列表以找到索引。只需使用
for i in range()
将列表的长度作为范围的大小,即可轻松完成此操作

indexes = [2, 5, 14, 16, 0, 9]
word = "AABBAA"

for i in range(len(indexes)):
    value = mappings[word[i]][indexes[i]]
    #Do whatever you want with the value here

我会这样做:

newlist = []
for i in range(len(string)):
    if string[i] == 'A':
        newlist.append(A_list[i])
    else:
        newlist.append(B_list[i])

这样,您就不必担心需要多长时间,您可以将不同列表的值映射到A_列表和B_列表下。

您可以使用包含列表的查找,从查找中查找目标列表,然后使用索引查找目标列表中的值

list_names = ['A', 'A', 'B', 'B', 'A', 'A']
list_indexes = [2, 5, 4, 6, 0, 9]
lists_lookup = {
    'A': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    'B': [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
}

result = []
for i in range(0, len(list_names)):
    target_list = lists_lookup[list_names[i]]
    index = list_indexes[i]
    result.append(target_list[index])
print(result)