首页 > 解决方案 > 如何打印多个数组/列表中的多个值,字符串仅在第一个输出前面,值之间用逗号分隔?

问题描述

我想将我的输出格式化为“Mode = 15, 59”。我对 Python 还很陌生,所以可能有一种完全更简单的方法,我只是还不知道或者如何更好地用谷歌搜索这个问题。感谢您的帮助。

请看下面的代码:

import numpy as np

dataset = [15, 21, 59, 15, 37, 59, 11, 41]
dataset.sort()

print(dataset)

unique = np.unique(dataset)
print(unique)

testing = []
for d in unique:
    testing.append(dataset.count(d))
print(testing)

combine = np.column_stack((unique,testing))
print(combine)

g = max(testing)

for i, j in combine:
    if j == g:
        #print('{}'.format(i), end='')
        #print("Mode = %s" %(i),end='')
        print('Mode =', i, end='')
        #print(i, end='')

输出:

[11, 15, 15, 21, 37, 41, 59, 59]
[11 15 21 37 41 59]
[1, 2, 1, 1, 1, 2]
[[11  1]
 [15  2]
 [21  1]
 [37  1]
 [41  1]
 [59  2]]
Mode = 15Mode = 59

标签: pythonpython-3.x

解决方案


combine = [
    [11, 1],
    [15, 2],
    [21, 1],
    [37, 1],
    [41, 1],
    [59, 2],
]
g = 2

modes = []

for i, j in combine:
    if j == g:
        modes.append(str(i))

print('Mode =', ', '.join(modes))

推荐阅读