从python中的列表中获取常用值

时间:2018-05-31 16:28:34

标签: python python-3.x list set

我有以下列表:

a=[{'list1': ['35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52']},
   {'list2': ['1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52']}]

我想从list1和list2中获取常用值。我写了

x = set(a[list_2015]).intersection(a[list_2016])

但它会抛出错误:

TypeError: list indices must be integers or slices, not tuple

我希望输出为:

{35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52}

1 个答案:

答案 0 :(得分:3)

这是一种方式:

res = set(map(int, a[0]['list1'][0].split(','))) & \
      set(map(int, a[1]['list2'][0].split(',')))

{35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52}

注意&运算符是set.intersection的语法糖。