python - 如何在 python 中使用索引在列中打印 1 和 0?

标签 python python-3.x indexing printing multiple-columns

我有一个 0 和 1 的列表,我想用标题和索引号将它们打印在两个不同的列中。像这样的东西。 列表 = [1,0,1,1,1,0,1,0,1,0,0]

ones      zeros
1 1       2 0
3 1       6 0
4 1       8 0
5 1       10 0
7 1       11 0
9 1

这是期望的输出。

我试过这个:

list = [1,0,1,1,1,0,1,0,1,0,0]

print('ones',end='\t')
print('zeros')

for index,ele in enumerate(list,start=1):
    if ele==1:
        print(index,ele,end="    ")
    elif ele==0:
        print("    ")
        print(index,ele,end="    ")
    else:
        print()

但这给出了这样的输出:

ones    zeros
1 1        
2 0    3 1    4 1    5 1        
6 0    7 1        
8 0    9 1        
10 0        
11 0   

如何获得所需的输出? 感谢您的帮助。

最佳答案

打印部分可以使用itertools.zip_longeststr.ljust、f-strings(格式化)和一些计算,用两个list来保存0 和 1 的索引:

l = [1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0]

ones, zeros = [], []
max_len_zeros = max_len_ones = 0

for index, num in enumerate(l, 1):
  if num == 0:
    zeros.append(index)
    max_len_zeros = max(max_len_zeros, len(str(index)))
  else:
    ones.append(index)
    max_len_ones = max(max_len_ones, len(str(index)))

from itertools import zip_longest

print('ones' + ' ' * (max_len_ones + 2) + 'zeros')

for ones_index, zeros_index in zip_longest(ones, zeros, fillvalue = ''):
  one = '1' if ones_index else ' '
  this_one_index = str(ones_index).ljust(max_len_ones)
  zero = '0' if zeros_index else ''
  this_zero_index = str(zeros_index).ljust(max_len_zeros)
  print(f'{this_one_index} {one}    {this_zero_index} {zero}')

输出:

ones   zeros
1 1    2  0
3 1    6  0
4 1    8  0
5 1    10 0
7 1    11 0
9 1        

0 多于 1 的列表:

In: l = [1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0]
Out:
ones    zeros
1  1    2  0
4  1    3  0
7  1    5  0
9  1    6  0
10 1    8  0
14 1    11 0
        12 0
        13 0
        15 0

具有相同数量的 0 和 1 的列表:

In: l = [1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1]
Out:
ones    zeros
1  1    2  0
3  1    4  0
5  1    6  0
8  1    7  0
9  1    10 0
11 1    13 0
12 1    14 0
15 1    16 0
18 1    17 0
20 1    19 0

关于python - 如何在 python 中使用索引在列中打印 1 和 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64592961/

相关文章:

python - 比较两个文件在 python 中的差异

python - 通过套接字发送和接收字节,具体取决于您的互联网速度

python - python3.6中根据提供的输入动态地将一个字典拆分为多个字典

indexing - 切片索引在 Rust 中如何工作?

javascript - Vue.js:如何读取计算函数中的 $index ?

python - Series.isin() 对于 'str' 和 'int' 类型值是否不一致?

具有可迭代和多个参数的 Python 多处理

python - Pandas - 操作系列和延迟

python - iPython azure 机器学习(经典)上缺少模块 tensorflow

mysql - MySQL索引中的 'name'和 'symbol'是什么?