python - 我怎样才能得到像 "1.number=85 2.number=97"这样的输出

标签 python python-3.x

我创建了一个列表并选择了 80 个随机元素。我的代码:

import random
a=list(range(1,100))
b=random.sample(a,80)
print(b)

我得到了这个输出

[85, 97, 32, 95, 35, 70, 57, 19, 71, 81, 39, 50, 93, 16, 13, 94, 36, 99, 38, 90, 54, 6, 29, 72, 63, 5, 64, 45, 24, 47, 33, 52, 44, 65, 23, 82, 21, 89, 74, 12, 51, 18, 78, 61, 86, 88, 62, 3, 96, 30, 69, 75, 84, 58, 9, 43, 31, 7, 28, 1, 91, 55, 37, 98, 73, 27, 92, 25, 68, 87, 41, 49, 2, 66, 77, 46, 53, 20, 4, 26]

如何将此输出转换为类似

1.number=85 2.number=97...80.number=26

最佳答案

有几个选项,但对您来说最清楚的可能是 print without the newline character或直接.join所需的子字符串

使用enumerate(my_iterable, 1)将允许您从中“提取”值,这些值是第一个可迭代中的下一个值的元组(示例中的 b )以及该值的索引(从 1 作为 enumerate 的第二个参数)

对于 [85, 97, 32, ...,您将提取 (85, 1), (97, 2), (32, 3)...可用于构建新字符串!

打印版

# your code
...
for index, value in enumerate(b, 1):  # begin enumeration at 1
    print("{}.number={} ".format(index, value), end="")
print("")  # end with a new line

加入版本
创建一个新的生成器表达式

" ".join("{}.number={}".format(i,v) for i, v in enumerate(b, 1))

解释器中的完整示例:

>>> b = [85, 97, 32, 95, 35, 70]
>>> print(" ".join("{}.number={}".format(i,v) for i, v in enumerate(b, 1)))
1.number=85 2.number=97 3.number=32 4.number=95 5.number=35 6.number=70

关于python - 我怎样才能得到像 "1.number=85 2.number=97"这样的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56478802/

相关文章:

python - 需要帮助使用 python 读取 tar 文件中的图像文件

python - max() 函数,获取最大元组

python - 如何设置 django 多对多字段接受 null

python - 命令 $python3 manage.py migrate 出错

Python 导入 - 解释

python-3.x - 当我在终端上运行 python -v 而不是 python -V 时会发生什么?

python - Flask:如何传递所有 GET 参数进行重定向?

python - 在不知道类名的情况下检查单独文件中类中的变量?

python - 如何在 Python 中遍历 cur.fetchall()

Python3查找2个列表中有多少差异才能相等