[英]how to print elements of a list whose sum is equal to a given number in python?
[英]How to print elements of list in python given a a fixed sample size?
我有一個包含名稱的列表 10,我將該列表中的 6 個名稱的隨機樣本存儲到另一個列表中。 我正在嘗試將第二個列表與索引號一起顯示為表格。 如何使用下面的代碼讓我的索引從 1 開始?
import random
list1 = [name1,name2,name3,name4,name5,name6,name7,name8,name9,name10]
list2 = random.sample(list1,6)
for i in range(0,len(list2)):
print(i,list2[i])
使用上面的方法,索引從 0 開始,但我需要它從 1 開始。如果將 for 循環范圍設置為從 1 開始,並設置 len(list2)+1,我會得到 index out of bounds 錯誤。
將enumerate()
與可選的start
參數一起使用:
for i, name in enumerate(list2, start=1):
print(i, name)
在range(0, len(list2))
中,0 是起始索引。 如果您希望從 1 開始,只需更改該值
import random
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
list2 = random.sample(list1, 6)
for i in range(1, len(list2) + 1):
print(i, list2[i - 1])
您也可以使用enumerate
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.