简体   繁体   English

如何使用列表列表创建表

[英]How to create a table using a list of lists

I'm trying to write a file where you have 2 rows, with the first row being numbers and the 2nd row being letters.我正在尝试编写一个有 2 行的文件,第一行是数字,第二行是字母。 As an example, I was trying to do this with the alphabet.例如,我试图用字母表来做到这一点。

list1=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
list2=list1+list1

abcList = [[],[]]

for i in range(len(list2)):
    i+=1
    if i % 5 == 0:
        if i>=10:
            abcList[0].append(str(i) + '     ')
        else:
            abcList[0].append(str(i) + ' ')
    elif i<=1:
        abcList[0].append(str(i) + ' ')
    else:
        abcList[0].append('  ')
for i,v in enumerate(list2):
    i+=1
    if i > 10:
        abcList[1].append(' '+v+' ')
    else:
        abcList[1].append(v+' ')

print(''.join(abcList[0]))
print(''.join(abcList[1]))

with open('file.txt','w') as file:
    file.write(''.join(abcList[0]))
    file.write('\n')
    file.write(''.join(abcList[1]))

The problem with the above setup is its very "hacky" (I don't know if its the right word).上述设置的问题是它非常“hacky”(我不知道它是否正确)。 It "works", but its really just modifying 2 lists to make sure they stack on top of one another properly.它“有效”,但实际上只是修改了 2 个列表以确保它们正确堆叠在一起。 The problem is if your list becomes too long, then the text wraps around, and stacks on itself instead of the numbers.问题是如果您的列表变得太长,那么文本会环绕,并堆叠在自身而不是数字上。 I'm looking for something a bit less "hacky" that would work for any size list (trying to do this without external libraries, so I don't want to use pandas or numpy).我正在寻找适用于任何大小列表的不那么“hacky”的东西(尝试在没有外部库的情况下执行此操作,所以我不想使用 pandas 或 numpy)。

Edit: The output would be:编辑: output 将是:

1       5         10
A B C D E F G H I J...etc.

Edit 2: Just thought I'd add, I've gotten this far with it so far, but I've only been able to make columns, not rows.编辑 2: 只是想补充一下,到目前为止,我已经做到了这一点,但我只能制作列,而不是行。

list1=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
list2=list1*2

abcList = [[],[]]

for i in range(len(list2)):
    i+=1
    if i % 5 == 0:
        if i>=5:
            abcList[0].append(str(i))
    elif i<=1:
        abcList[0].append(str(i))
    else:
        abcList[0].append('')
for i,letter in enumerate(list2):
    abcList[1].append(letter)

for number, letters in zip(*abcList):
    print(number.ljust(5), letters)

However, this no longer has the wrapping issues, and the numbers line up with the letters perfectly.但是,这不再有包装问题,并且数字与字母完美对齐。 The only thing now is to get them from columns to rows.现在唯一要做的就是让它们从列到行。

Output of above is:上面的 Output 是:

1     A
      B
      C
      D
5     E
      F
      G
      H
      I
10    J

I mean, you could do something like this:我的意思是,你可以这样做:

file_contents = """...""" # The file contents. I not the best at file manipulation


def parser(document):  # This function will return a nested list
    temp = str(document).split('\n')
    return [[line] for line in temp]  # List comprehension
parsed = parser(file_contents) 
# And then do what you want with that

Your expected output is a bit inconsistent, since in the first one, you have 1, 6, 11, 16... and in the second: 1, 5, 10, 15.... So I have a couple of possible solutions:您预期的 output 有点不一致,因为在第一个中,您有 1、6、11、16 1, 6, 11, 16...而在第二个中:1、5、10、15 1, 5, 10, 15....所以我有几个可能的解决方案:


print(''.join(['  ' if n%5 else str(n+1).ljust(2) for n in range(len(list2))]))
print(''.join([c.ljust(2) for c in list2]))

Output: Output:

1         6         11        16        21        26        31        36        41        46        51  
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

print(''.join(['  ' if n%5 else str(n).ljust(2) for n in range(len(list2))]))
print(''.join([c.ljust(2) for c in list2]))

Output: Output:

0         5         10        15        20        25        30        35        40        45        50  
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 

print(''.join(['1 ']+['  ' if n%5 else str(n).ljust(2) for n in range(len(list2))][1:]))
print(''.join([c.ljust(2) for c in list2]))

Output: Output:

1         5         10        15        20        25        30        35        40        45        50  
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

If you are wanting to keep variable width strings aligned, you could use string formatting with a width equal to the maximum of the widths of the individual items in that position.如果您想保持可变宽度字符串对齐,您可以使用宽度等于 position 中单个项目宽度的最大值的字符串格式。 (This example will work with more than any number of lists, by the way.) (顺便说一下,这个例子适用于多于任何数量的列表。)

list1 = ["", "5", "", "10", "", "4"]
list2 = ["A", "B", "C", "D", "EE", "F"]

lists = [list1, list2]

widths = [max(map(len, t)) for t in zip(*lists)]

for lst in lists:
    line = " ".join("{val:{width}s}".format(val=val, width=width)
                    for val, width in zip(lst, widths))
    print(line)

gives:给出:

  5   10    4
A B C D  EE F

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

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