如何在Python中生成列表的所有分组(最好是itertools)

时间:2016-09-25 06:18:23

标签: python-3.x

鉴于我有一个序列,例如1 2 3 4如何使用itertools从中生成以下组:

(1)(2)(3)(4)

(1 2)(3)(4)

(1)(2 3)(4)

(1)(2)(3 4)

(1 2)(3 4)

(1 2 3)(4)

(1)(2 3 4)

(1 2 3 4)

顺序并不重要......我对它们进行分组的方式是使用分隔符:最初我使用三个分隔符将它们分成四组,然后我使用两个分隔符分成三组(2种分割方式)分三组)等等

如果itertools无法实现,我还可以生成它吗?

1 个答案:

答案 0 :(得分:3)

使用列表中的 n 项目,列表项之间有 n-1 个位置,可能存在或可能不存在分隔。因此,我们可以让每个分组对应一个 n-1 位列表,其中1表示分隔,def generate_groupings(xs): for bits in range(2 ** (len(xs)-1)): # int representing n-1 bits grouping = [(xs[0],)] # grouping starts with first item for x in xs[1:]: # for each remaining item... bits, b = divmod(bits, 2) # pop one bit off of the list if b: # case 1: no separation grouping = grouping[:-1] + [grouping[-1] + (x,)] else: # case 0: separation grouping += [(x,)] yield grouping list(generate_groupings([1,2,3])) # [[(1,), (2,), (3,)], [(1, 2), (3,)], [(1,), (2, 3)], [(1, 2, 3)]] 表示不分离。

(1+2+3)*1 + (1+2)*2 + (3)*1 + (1)*1 + (2+3)*2 +(1+2+3)*3

回答你的后续问题

  

如何从上面的表单列表中获取值:*,即组sum(sum(g)*len(g) for gs in generate_groupings([1,2,3]) for g in gs) # 44 组长度中元素的总和

orgID = "quickstart" -- IoT Foundation organization ID 
broker = "test.mosquitto.org"   --orgID..".messaging.internetofthings.ibmcloud.com" -- IP or hostname of IoTF service
mqttPort = 1883 -- MQTT port (default 1883: non-secure)
userID = "" -- blank for quickstart
userPWD = "" -- blank for quickstart
macID = "18fe34e1b007" -- unique Device ID or Ethernet Mac Address <==== Modify this!
clientID = ":esp8266:18fe34e1b007" -- Client ID
count = 0 -- Test number of mqtt_do cycles
mqttState = 0 -- State control
topic = "topic/temp/motion"
led = 4
--gpio.mode(led,gpio.OUTPUT)
--dht sensor settings------------------------------
 pin = 1
-- PIR initialization section
pir = 2
x= 0 -- variable for sending motion detection information in "0 or 1"

function DHT_do()
status, temp, humi, temp_dec, humi_dec = dht.read(pin)
--gpio.write(led, gpio.LOW)
end


 function mqtt_do()
 count = count + 1 -- tmr.alarm counter
------------------------------------------- pir conditional code
if gpio.read(pir) ~= last_state then
        last_state = gpio.read(pir)
        if last_state == 1 then
        print("ON")
        x = 1
        gpio.write(led,gpio.HIGH)
        else
        print("OFF")
        x = 0
       gpio.write(led,gpio.LOW)

m:publish(topic,x, 0, 0,
 function(conn)
  print(x)
  print("temp_data:"..temp)