0

我想知道如何将一个列表中的每个项目与第二个列表中的相应索引对齐。到目前为止,这是我的代码:

letters=['a','ab','abc','abcd','abcde','abcdef','abcdefg','abcdefgh','abcdefghi','abcdefghij']
numbers=[1,2,3,4,5,6,7,8,9,10]

for x in range(len(letters)):
    print letters[x]+"----------",numbers[x]

这是我得到的输出:

a---------- 1
ab---------- 2
abc---------- 3
abcd---------- 4
abcde---------- 5
abcdef---------- 6
abcdefg---------- 7
abcdefgh---------- 8
abcdefghi---------- 9
abcdefghij---------- 10

这是我想要的输出:

a---------- 1
ab--------- 2
abc-------- 3
abcd------- 4
abcde------ 5
abcdef----- 6
abcdefg---- 7
abcdefgh--- 8
abcdefghi-- 9
abcdefghij- 10
4

4 回答 4

3

您可以使用字符串格式:

for left, right in zip(letters, numbers):
    print '{0:-<12} {1}'.format(left, right)

和输出:

a----------- 1
ab---------- 2
abc--------- 3
abcd-------- 4
abcde------- 5
abcdef------ 6
abcdefg----- 7
abcdefgh---- 8
abcdefghi--- 9
abcdefghij-- 10
于 2013-04-28T21:34:27.783 回答
0
letters=['a','ab','abc','abcd','abcde','abcdef','abcdefg','abcdefgh','abcdefghi','abcdefghij']
numbers=[1,2,3,4,5,6,7,8,9,10]

for x in range(len(letters)):
    print '{0:11}{1}'.format(letters[x],numbers[x]).replace(' ','-');


a----------1
ab---------2
abc--------3
abcd-------4
abcde------5
abcdef-----6
abcdefg----7
abcdefgh---8
abcdefghi--9
abcdefghij-10
于 2013-04-28T21:46:12.037 回答
0

像这样使用string.formatting

def solve(letters,numbers):
    it=iter(range( max(numbers) ,0,-1))
    for x,y in zip(letters,numbers):
        print "{0}{1} {2}".format(x,"-"*next(it),y)
   ....:         

In [38]: solve(letters,numbers)
a---------- 1
ab--------- 2
abc-------- 3
abcd------- 4
abcde------ 5
abcdef----- 6
abcdefg---- 7
abcdefgh--- 8
abcdefghi-- 9
abcdefghij- 10
于 2013-04-28T21:34:16.487 回答
0
letters=['a','ab','abc','abcd','abcde','abcdef','abcdefg','abcdefgh','abcdefghi','abcdefghij']

for c,x in enumerate(letters, start=1):
    print x+("-"*(10-c))+" %s" % c

a--------- 1
ab-------- 2
abc------- 3
abcd------ 4
abcde----- 5
abcdef---- 6
abcdefg--- 7
abcdefgh-- 8
abcdefghi- 9
abcdefghij 10
于 2013-04-28T21:35:59.797 回答