简体   繁体   English

使用for循环python创建简单表

[英]Created simple table with for-loop python

Im just trying to create simple table with following this code 我只是试图按照以下代码创建简单的表

n = 0
x = ["list1","list2","list3","list4"]
for y in x:
    n+=1
    h="{}. {}".format(n,y) + '   ' + "{}. {}".format(n+n,y)
    print(h)

And output i got 和我得到的输出

1. list1  5. list1
2. list2 6. list2
3. list3  7. list3
4. list4  8. list4

What should i do to got output like this 我应该怎么做才能得到这样的输出

1. list1  3. list3
2. list2  4. list4

Im just beginning and so confused to solved it,thanks for who can answer my issue. 我刚刚开始,很困惑地解决了它,感谢谁能回答我的问题。

The below should give you what you are looking for, no matter how long the list is. 无论列表多长,下面的内容都会为您提供所需的信息。 There may be a more efficient way than this but this way breaks it down into its parts, so essentially you need to find the halfway point in the list and print the respective value on the right. 可能有比这更有效的方法,但是这种方法将其分解为各个部分,因此从本质上讲,您需要在列表中找到中间点,并在右侧打印相应的值。

x = ["list1","list2","list3","list4", "list5",]

if len(x) % 2 == 1 :
    half = int((len(x) + 1) / 2)
else:
    half = int(len(x) / 2)

for i in range(half):
    if half > len(x) / 2:
        if i == half - 1:
            h = "{}. {}".format (i + 1 , x[i])
        else:
            h = "{}. {}".format (i + 1 , x[i]) + '   ' + "{}. {}".format (half + (i + 1) , x[int (len (x) / 2) + i + 1])
    else:
        h = "{}. {}".format (i + 1 , x[i]) + '   ' + "{}. {}".format (half + (i + 1), x[int (len (x) / 2) + i])
    print(h)

I have also taken into account lists that have an odd number of elements like the above example for x , which will give you the following output 我还考虑了具有奇数个元素的列表,例如上面x示例,这将为您提供以下输出

1. list1   4. list4
2. list2   5. list5
3. list3

Something like this? 像这样吗

import math
x = ["list1","list2","list3","list4", "list5", "list6", "list7"]
y = math.ceil(len(x)/2)
for i, j in enumerate(x[:math.ceil(len(x)/2)], start=1):
    try:
        print("{}. {}".format(i, j) + '     '"{}. {}".format(i+math.ceil(len(x)/2), x[y]))
    except:
        print("{}. {}".format(i, j))
    y +=1

Output: 输出:

1. list1     5. list5
2. list2     6. list6
3. list3     7. list7
4. list4

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

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