有没有办法避免嵌套循环

时间:2019-04-11 03:25:36

标签: python python-3.x loops

我得到了两个不同的数据,我想知道是否有一种方法可以在不使用嵌套循环的情况下获取特定数据

firstdata = [[["key"],["value"]],
              [[2],["two"]],
              [[3],["three"]]]
seconddata = [[[key],["artimatic"]],
               [[2],["0+2"]],
               [[2],["1+1"]],
               [[3],["0+3"]],
               [[3],["1+2"]],
               [[3],["2+1"]]]
 //nested loop solution would look like this
 for x in firstdata:
     for y in seconddata:
         print(x[1])
         if x[0]==y[0]:
             print(y)

有没有一种替代解决方案,可以不用嵌套循环就可以循环第二个数据?

3 个答案:

答案 0 :(得分:1)

**好吧,我假设firstdata和seconddata的数据结构相同:


firstdata_dict = {x[0][0]: x[1][0] for x in firstdata}
seconddata_dict = {}

for data in seconddata:

   if not seconddata_dict.has_key(data[0][0]):
       seconddata_dict[data[0][0]] = []
   seconddata_dict[data[0][0]].append(data[1][0])

for key, value in firstdata_dict.items():
    if seconddata_dict.get(key):
       # key match add your algo 
       print seconddata_dict[key]

Output:
['0+2', '1+1']
['0+3', '1+2', '2+1']
['artimatic']

答案 1 :(得分:0)

首先将列表转换为字典。这里的键是数字2和3,值是与列表中特定键关联的字符串列表

def convert_to_dct(lst):

    dct = {}
    for x in lst:
        for i in range(len(x)):
            key = x[0][0]
            value = x[1][0]
            if key in dct:
                dct[key].append(value)
            else:
                dct[key] = []

    return dct

此函数将列表转换如下

firstdata = [[["key"],["value"]],
              [[2],["two"]],
              [[3],["three"]]]
seconddata = [[["key"],["artimatic"]],
               [[2],["0+2"]],
               [[2],["1+1"]],
               [[3],["0+3"]],
               [[3],["1+2"]],
               [[3],["2+1"]]]

firstdict = convert_to_dct(firstdata)
seconddict = convert_to_dct(seconddata)

print(firstdict)
print(seconddict)
#{'key': ['value'], 2: ['two'], 3: ['three']}
#{'key': ['artimatic'], 2: ['0+2', '1+1', '1+1'], 3: ['0+3', '1+2', '1+2', '2+1', '2+1']}

然后获得最终结果,做

for key in firstdict.keys():
   if key in seconddict.keys():
       print(seconddict[key])
#['artimatic']
#['0+2', '1+1', '1+1']
#['0+3', '1+2', '1+2', '2+1', '2+1']

答案 2 :(得分:0)

我认为这两个答案不能正确理解问题,因此您可以开始:

创建数据

firstData = [[["key"],["value"]],
              [[2],["two"]],
              [[3],["three"]]]
secondData = [[['key'],["artimatic"]],
               [[2],["0+2"]],
               [[2],["1+1"]],
               [[3],["0+3"]],
               [[3],["1+2"]],
               [[3],["2+1"]]]

然后

firstdata_dict = {x[0][0]: x[1][0] for x in firstData} #Creates the dictionary of first Data

然后进行计算

for element in secondData:
  if (element[0][0] in firstdata_dict): #Checks in a hashMap and is thus done in O(1) generally
    print(element)