使用字典替换列表中的值?

时间:2017-07-29 05:53:58

标签: list python-3.x dictionary

如果我有一个包含{'a':'b', 'b':'c', 'c':'d'}的字典,并且我想使用这些键将列表l = ['z', 'q', 'f']的内容替换为相应的值,我该怎么做?

当我第一次尝试解决这个问题时,我想我可以在dict中输入类似list [i] = get。(i)的内容。但这似乎不起作用。

2 个答案:

答案 0 :(得分:1)

my_dict = {'a':'b', 'b':'c', 'c':'d'}

l = ['b', 'c', 'a']

new_list = [my_dict[x] for x in l]

当然,假设您拥有l列表中每个元素的密钥。然后,您可以执行l = list(new_list)。如果您仍想使用l变量。

答案 1 :(得分:0)

下面应该考虑角落情况......

  • 字典中出现的循环密钥(例如{' a':''''''''' ; C':' d'})
  • 键在列表中重复多次(例如[' b',' c',' a',' z',& #39; b',' c'])
  • 列表中的
  • 键不存在于词典的键中(例如' z')

以下是两个解决方案,一个是通过更新相同的列表,另一个是通过创建新列表。

更新相同的列表

void sort() {
   const int N = 6;
   int  *keys = new  int[N]; // = { 1,   4,   2,   8,   5,   7};
   char *vals = new char[N]; // = {'a', 'b', 'c', 'd', 'e', 'f'};
   int  *addr = new  int[N]; // = { 1,   2,   3,   4,   5,   6};
   keys[0]=1; keys[1]=4; keys[2]=2; keys[3]=8; keys[4]=5; keys[5]=7;
   vals[0]='a'; vals[1]='b'; vals[2]='c'; vals[3]='d'; vals[4]='e'; vals[5]='f';
   addr[0]=1; addr[1]=2; addr[2]=3; addr[3]=4; addr[4]=5; addr[5]=6;

   int *d_keys, *d_addr;
   char *d_vals;
   CUDA_SAFE(cudaMalloc((void **)&d_keys, N * sizeof(int)));
   CUDA_SAFE(cudaMalloc((void **)&d_addr, N * sizeof(int)));
   CUDA_SAFE(cudaMalloc((void **)&d_vals, N * sizeof(char)));
   CUDA_SAFE(cudaMemcpy(d_keys, keys, N * sizeof(int), cudaMemcpyHostToDevice));
   CUDA_SAFE(cudaMemcpy(d_vals, vals, N * sizeof(char), cudaMemcpyHostToDevice));
   CUDA_SAFE(cudaMemcpy(d_addr, addr, N * sizeof(int), cudaMemcpyHostToDevice));

   auto it = thrust::make_zip_iterator(thrust::make_tuple(d_vals, d_addr));

   thrust::sort_by_key(thrust::device, d_keys, d_keys+N, it);

   CUDA_SAFE(cudaMemcpy(keys, d_keys, N * sizeof(int), cudaMemcpyDeviceToHost));
   CUDA_SAFE(cudaMemcpy(vals, d_vals, N * sizeof(char), cudaMemcpyDeviceToHost));
   CUDA_SAFE(cudaMemcpy(addr, d_addr, N * sizeof(int), cudaMemcpyDeviceToHost));

   printf("Keys: "); for (int i = 0; i < N; i++) printf("%d ", keys[i]); printf("\n");
   printf("Vals: "); for (int i = 0; i < N; i++) printf("%c ", vals[i]); printf("\n");
   printf("Addr: "); for (int i = 0; i < N; i++) printf("%d ", addr[i]); printf("\n");
}

创建新列表

dictionary = {'a':'b', 'b':'c', 'c':'d'}
l = ['b', 'c', 'a', 'z', 'b', 'c']

print(l)
position = 0
for item in l:
    if item in dictionary.keys():
        l[position] = dictionary[item]
    position = position + 1
print(l)

示例运行

dictionary = {'a':'b', 'b':'c', 'c':'d'}
l = ['b', 'c', 'a', 'z', 'b', 'c']
nl = []
for item in l:
    if item in dictionary.keys():
        nl.append(dictionary[item])
    else:
        nl.append(item)
print(l)
print(nl)