代码之家  ›  专栏  ›  技术社区  ›  user7575724

按特定顺序打印列表中的项目,python

  •  0
  • user7575724  · 技术社区  · 7 年前

    我正在尝试按特定顺序打印两个列表(l、val)中的项目。我的代码在这里。。

    我试着在(.)通过将其带到变量,但在执行过程中会对其进行更新。

    使用a.b1/(.)打印项目时介于两者之间,需要将其定位在(.)正如我所做的,以及(.)应使用更多的空格打印,直到itwm的第一部分保持不变,例如,对于像a.b1/、a.b2/、a.b3/这样的项目,应打印第一个“a”,并与左侧b1、b2、b3等距离打印,最后一个“a”应以相同的距离打印,第一个“a”应与左侧保持相同距离。

    我的代码在这里。

    l = ['a1','b2','c3','d4','e5','a.b1/','a.b2/','a.b3/','e5','f6','g7','q.a1/','q.a2/','q.a3/','h','i','j']
    val = ['None','None','None','None','None','None','None','None','None','None','None','None','None','None','None','None','None','None','None']
        for i in range(0,len(l)):
            if l[i][-1:] == '/':
                l_p = l[i].split('.')[0]
                l_c = (l[i].split('.')[1]).strip('/')
                print('       '+'%s'%l_p+' \n')
                print('         '+l_c+' '+'%s'%val[i]+' '+l_c+' '+'\n')
                print('        '+'%s'%l_p+' \n')
            else:
                print('       '+l[i]+' '+'%s'%val[i]+' '+l[i]+' '+'\n')
    

    我的输出是

       a1 None a1 
       b2 None b2 
       c3 None c3 
       d4 None d4 
       e5 None e5 
       a 
         b1 None b1 
        a 
       a 
         b2 None b2 
        a 
       a 
         b3 None b3 
        a 
       e5 None e5 
       f6 None f6 
       g7 None g7 
       q 
         a1 None a1 
        q 
       q 
         a2 None a2 
        q 
       q 
         a3 None a3 
        q 
       h None h 
       i None i 
       j None j   
    

    我的预期输出是:

      a1 None a1
      b2 None b2
      c3 None c3
      d4 None d4
      e5 None e5
      a
        b1 None b1
        b2 None b2
        b3 None b3
      a
      e5 None e5
      f6 None f6
      g7 None g7
      q
        a1 None a1
        a2 None a2
        a3 None a3
      q
      h None h
      i None i
      j None j
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Mr. T Andres Pinzon    7 年前

    你必须跟踪你所在的类别,即点之前的部分。如果您不想在每个块的末尾再次打印出类别,这会更容易,但现在我们开始:

    prev_cat = ""
    for i, item in enumerate(l):     #iterate over the list
        if item.endswith("/"):       #identify category and category element, set tabulator
            curr_cat, printitem = item[:-1].split(".")
            tabulator = "    "    
        else:
            curr_cat, printitem, tabulator = "", item, ""
    
        #identify category, changes in category, print categories
        if curr_cat and (curr_cat != prev_cat):    
            if prev_cat:
                print(prev_cat)
            print(curr_cat)
        elif not curr_cat and prev_cat:
            print(prev_cat)
    
        prev_cat = curr_cat
        #print category items from both lists
        print(tabulator + " ".join([printitem, val[i], printitem]))  
    
    if curr_cat:    #close the last category, if necessary
        print(curr_cat)      
    

    它不检查,如果 val 有足够的元素可打印,或者 l 包含字符串或如果 l 结束于 / 实际上正好包含由一个点分隔的两个部分。这被视为您问题中指定的给定。