简体   繁体   English

如何并排打印两个不同大小的列表?

[英]How to print two lists of different size side by side?

I have two lists of different length that I want to print side by side, separated by a tab.我有两个不同长度的列表,我想并排打印,用制表符分隔。 As an example:举个例子:

a_list = ["a","b","c","d","e"]
b_list = ["f","g","h","i","j","k","l","m","n"]

I tried:我试过了:

print('A-list:'+ '\t' + 'B-list:')
for i in range(len(b_list)):
    print(a_list[i] + '\t' + b_list[i])

I off course get an "out of range-trace" back because one list is shorter.我当然会得到一个“超出范围的跟踪”,因为一个列表更短。 I do not wish to use zip.不想使用 zip。

your code is rasing IndexError because the length of b_list is greater than the length of a_list , for this, you could use a try except statement:您的代码正在b_list IndexError因为b_list的长度大于a_list的长度,为此,您可以使用try except语句:

for i in range(max(len(b_list), len(a_list))):
    try:
        print(f"{a_list[i]}\t", end="")
    except IndexError:
        print(f" \t", end="")
    try:
        print(f"{b_list[i]}\t")
    except IndexError:
        print(f" \t")

output:输出:

a   f
b   g
c   h
d   i
e   j
    k
    l
    m
    n

This is a possible solution.这是一个可能的解决方案。 It doesn't matter if a_list is longer or shorter than b_list . a_listb_list长还是短都没有b_list

def get(lst, idx):
    try:
        return lst[idx]
    except:
        return " "

a_list = ['a','b','c','d','e'] 
b_list = ['f','g','h','i','j','k','l','m','n']

result = []

for i in range(min(len(a_list), len(b_list))):
    result.append(get(a_list, i))
    result.append(get(b_list, i))

for i in range(min(len(a_list), len(b_list)), max(len(a_list), len(b_list))):
    result.append(get(a_list, i))
    result.append(get(b_list, i))

print('\n'.join('\t'.join((result[i], result[i+1]))
                          for i in range(0, len(result), 2)))

This prints the expected output:这将打印预期的输出:

a   f
b   g
c   h
d   i
e   j
    k
    l
    m
    n

without any extra loop:没有任何额外的循环:

list_a = ["A", "B", "C"]
list_b = ["1", "2", "3", "4"]
len_a = len(list_a)
len_b = len(list_b)
i = 0
while True:
    if i < len_a:
        print(list_a[i], end="")
    if i < len_b:
        print("\t", list_b[i], end="")
    print()
    i += 1
    if i > max(len_a, len_a):
        break
def iterate(a_list, b_list):
  # iterate through short list
  min_length = min(((len(a_list), len(b_list)))) 

  for i in range(min_length):
    print('{}\t{}'.format(a_list[i], b_list[i]))

  # print remaining items accordingly
  if i + 1 == len(a_list):
    for item in b_list[i+1:]:
      print('\t{}'.format(item))  
  else:
    for item in a_list[i+1:]:
      print(item) 

I advise use the string method format which allows you to have elements of any kind in your lists.我建议使用字符串方法格式,它允许您在列表中包含任何类型的元素。

In all solutions, the trick is to go through the longest list and use an empty space for missing entries in the shorter list.在所有解决方案中,诀窍是遍历最长的列表并为较短列表中的缺失条目使用空白空间。

For example:例如:

a_list = ['a','b','c','d','e'] 
b_list = ['f','g','h','i','j','k','l','m','n']

for i in range(max(len(a_list),len(b_list))):
    a = a_list[i:i+1] or [""]
    b = b_list[i:i+1] or [""]
    print(a[0]+"\t"+b[0])

If you're not concerned with memory usage, you could also pad the lists with blanks in order to have a simpler printing process that assumes lists of same sizes:如果您不关心内存使用情况,您还可以用空白填充列表,以便在假设列表大小相同的情况下进行更简单的打印过程:

padding  = len(b_list)-len(a_list)
a_padded = a_list + [""]*padding
b_padded = b_list + [""]*-padding
for i in range(len(a_padded)):
    print(a_padded[i]+"\t"+b_padded[i])

You could try this:你可以试试这个:

test1 = [1, 2, 3, 4]
test2 = [1, 2, 3, 4, 5]
test3 = [1, 2]

while test or test2 or test3:
    print(test.pop() if test else '',\
          test2.pop() if test2 else '',\
          test3.pop()if test3 else '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM