[英]Inserting lists to a nested-list within a for-loop in Python
作為一個習慣用 Python(我目前唯一了解的語言)編寫的項目,我正在編寫一個 Cribbage 分數計數器。
我從一組 5 個數字中找到了所有 3、4 和 5 個長度的子集。 子集都按數字順序排序。 下面的函數應該按順序查找數字子集,例如 [1, 2, 3] 或 [3, 4, 5]。
def straight_counter(subset, length):
straights = []
a = 0 # Variable for incremental increase
for i in range(0, length - 2): # Select one of the first three numbers of a set of 3-5 (which are already ordered)
run = 1
x = 1
while i + x < length: # Ensure that we do not go beyond the final index
if subset[i + x - 1] + 1 == subset[i + x]: # Is the next number one greater than the currently selected number
run += 1 # Count how many numbers we have in order (will be maximum of 5)
x += 1
else:
break
這是我嘗試僅獲取按順序排列的所有數字的子集的地方。 但是,當我嘗試將它添加到嵌套列表中時,我每次都在列表的第一個索引上寫字,並且打印時列表只有一個項目長
if run == length: # If the run of consecutive numbers uses all of the numbers e.g [1, 2, 3] and not [1, 2, 4]
straights.insert(a, subset) # I would like to add the list as the first index of a different list
a += 1 # Increase a so that the next valid subset will be at the next index
print(straights)
發生這種情況是否有明顯的原因? 或者也許有一種更簡潔的方法來嘗試這個。 謝謝
例如從輸入的數字列表
[1, 1, 2, 3, 4]
我正在嘗試創建一個嵌套列表:
[[1, 2, 3], [1, 2, 3], [2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]。
都是長度大於等於 3 的連續數的集合。
您可以在下面找到解決方案。 這個想法是找到第一個和最后一個連續集合。
# -*-coding:Utf-8 -*
data = [1, 4, 5, 6, 10, 15, 16, 17, 18, 22, 25, 26, 27, 28]
from operator import itemgetter
from itertools import groupby
for k, g in groupby(enumerate(data), lambda ix : ix[0] - ix[1]):
group = list(map(itemgetter(1), g))
print ((group[0], group[-1]))
在這一點上你得到這個:
(1, 1)
(4, 6)
(10, 10)
(15, 18)
(22, 22)
(25, 28)
然后您只需要選擇正確的並保留它們(差異高於 2)。 如果需要,您還可以重新創建列表。
OP:您提到了 5 張牌,即“保留手牌”+ 起始牌或嬰兒床 + 起始牌。 有更多的時候呢? 具體來說,The Play。 展望未來,是否應該將同一段代碼用於這兩個目的?
想象一下玩家有 A-3-5-7 和 2-3-4-6
最大數量是 (1+3+5+7)+(2+3+4+6) => 31。雖然組合的數量和打牌順序是有限的,但它有點棘手。
順便說一句:作為 Cribbage 瑣事的一點(雙關語),The Sting 將在 Flix (09/02) 和 Showtime (09/07) 上播出。 這是您會在屏幕上看到 Cribbage 播放的少數幾個地方之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.