【问题标题】:Iterating through a list of tuples遍历元组列表
【发布时间】:2017-04-19 04:45:25
【问题描述】:

遍历元组列表 [('a', 4), ('b', 5), ('c', 1), ('d', 3), ('e', 2), ('f',6)]

尝试将匹配对作为输出

任何指导将不胜感激。

这是我目前所拥有的:

data = [('a', 4), ('b', 5), ('c', 1), ('d', 3), ('e', 2), ('f',6)]
new_list = []
vowels = 'aeiou'
consonants = 'bcdfghjklmnpqrstvxw'
consonants = list(consonants)
vowels = list(vowels)
for idx, (a,b) in enumerate(data):
    if (a) in vowels or (a) in consonants and (b) % 3 == 0:
        new_list.append(idx)
print tuple(new_list)

这是我卡住的地方

【问题讨论】:

  • 对不起,我不太明白你的问题。 [(0,4), (1,2), (3,4)] 是什么意思?项目 (3,4) 的数量加起来是 5,这似乎不是 3 的倍数。
  • 感谢您的捕获,它应该是 (3,6)
  • 我认为您的结果应该有(5,3)(3,5) 但不是(3,4)
  • 您需要 2 个循环。对于列表中的每个元素,遍历列表以查找其所有匹配项。

标签: python python-2.7 python-3.x tuples


【解决方案1】:

这是一个简单的方法,您可以稍后扩展:

nums = [('a', 4), ('b', 5), ('c', 1), ('d', 3), ('e', 2), ('f',6)]
vowels = ['a','e','i','o','u']
results = []
for k,v in enumerate(nums):
    for i,j in enumerate(nums[:]):
        if v == j:
            continue
        if v[0] in vowels and j[0] in vowels:
            if (v[1]+j[1]) % 3 == 0:
                if (i,k) not in results:
                    results.append((k,i))
        if v[0] not in vowels and j[0] not in vowels:
            if (v[1]+j[1]) % 3 == 0:
                if (k,i) not in results:
                    results.append((i,k))
print(results)

【讨论】:

    【解决方案2】:
    data = [('a', 4), ('b', 5), ('c', 1), ('d', 3), ('e', 2), ('f',6)]
    new_list = []
    vowels = 'aeiou'
    for idx,(a,b) in enumerate(data):
         for _idx,(_a,_b) in enumerate( data[idx+1:]):
               if bool(a in vowels)==bool(_a in vowels) and(b+_b)%3==0:
                   new_list.append((idx,_idx+idx+1))
    

    【讨论】:

      【解决方案3】:
      a = [('a', 4), ('b', 5), ('c', 1), ('d', 3), ('e', 2), ('f',6)] 
      c = np.asarray([[int(e[0] in 'aeiou'), e[1]] for e in a])
      e = (c[:,None] + c) % 3
      f = np.asarray(np.where((e[...,0]%2==0) & (e[...,1]==0))).T.tolist()
      print set([tuple(sorted(i)) for i in f if i[0]!=i[1]])
      
      set([(1L, 2L), (3L, 5L), (0L, 4L)])
      

      【讨论】:

        猜你喜欢
        • 2019-11-16
        • 2013-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-02
        • 2019-03-17
        相关资源
        最近更新 更多