为什么Python列表乘法创建包含多个元素的单个列表?

时间:2019-10-30 20:46:49

标签: python list

在python中,['a'] * 4给出['a', 'a', 'a', 'a']。为什么不[['a'], ['a'], ['a'], ['a']]

3 个答案:

答案 0 :(得分:5)

因为,就像重复整数乘法一样,用lis乘法也是重复串联。

>>> ['a'] + ['a'] + ['a'] + ['a']
['a', 'a', 'a', 'a']
>>> ['a'] * 4
['a', 'a', 'a', 'a']
>>> 4 * ['a']
['a', 'a', 'a', 'a']

这也遵守其他各种法律:

  • 分发:lst * n + lst * m == lst * (n + m)
  • 零属性:lst * 0 == 0 * lst == []
  • 多重身份:lst * 1 == lst

以上内容也与空白列表[]为加成身份一致,

['a'] + [] == [] + ['a'] == ['a']

因为

['a'] + [] == ['a'] * 1 + ['a'] * 0  # zero property and multiplicative identity
           == ['a'] * (1 + 0)        # distribution
           == ['a'] * 1              # integer addition
           == ['a']                  # multiplicative identity

可以说,list * int不应在 all 处定义。为了快速生成n个相同元素的列表,主要用例是使用列表推导(稍后添加到语言中)更安全地完成。 [x] * n创建对单个元素x的引用列表,如果x可变,通常不是。另一方面,[x for _ in range(n)]创建由x定义的独立对象的列表,当x可变时,就是您想要的。

答案 1 :(得分:1)

类似于与数字carpet_remaining = 2 if (carpet_remaining > 0): for i in range(100): newQ,newT = currentValues() print(newQ) print(newT) # Attempt to start a mission: max_retries = 3 for retry in range(max_retries): try: agent_host.startMission( my_mission, my_mission_record ) break except RuntimeError as e: if retry == max_retries - 1: print("Error starting mission:",e) exit(1) else: time.sleep(2) # Loop until mission starts: print("Waiting for the mission to start ", end=' ') world_state = agent_host.getWorldState() while not world_state.has_mission_begun: print(".", end="") time.sleep(0.1) world_state = agent_host.getWorldState() for error in world_state.errors: print("Error:",error.text) print() print("Mission running ", end=' ') agent_host.sendCommand("pitch 0") #Start looking downward slowly time.sleep(1) #Wait a second until we are looking in roughly the right direction while world_state.is_mission_running: #may have to restart mission. look into it print(".", end="") time.sleep(0.1) world_state = agent_host.getWorldState() for error in world_state.errors: print("Error:",error.text) if world_state.number_of_observations_since_last_state > 0: msg = world_state.observations[-1].text observations = json.loads(msg).get("LineOfSight") #print(observations) # 1. Determine block type #2. Make a switch case based on block type that determines to set input nodes. # for example if block type is 'grass' then grass node is 1, and all other nodes 0. # 3. Run forward propagation. # 4. Look at output nodes figure out node with highest value # 5. execute action based on output nodes #botsEyes = observations.get("LineOfSight") #print (botsEyes) botsEyes = observations.get("type") # print('The bot is looking at: ',botsEyes) if botsEyes == ("lapis_block"): inputValues = [1, 0, 0, 0] lapisNode = 1 grassNode = 0 fenceNode = 0 carpetNode = 0 elif botsEyes == ("grass"): inputValues = [0, 1, 0, 0] lapisNode = 0 grassNode = 1 fenceNode = 0 carpetNode = 0 elif botsEyes == ("spruce_fence"): inputValues = [0, 0, 1, 0] lapisNode = 0 grassNode = 0 fenceNode = 1 carpetNode = 0 elif botsEyes == ("carpet"): inputValues = [0, 0, 0, 1] lapisNode = 0 grassNode = 0 fenceNode = 0 carpetNode = 1 else: inputValues = [0, 0, 0, 0] lapisNode = 0 grassNode = 0 fenceNode = 0 carpetNode = 0 print("Neural Net values: ",inputValues) X = np.array((inputValues,), dtype = float) #print ("Actual Output: \n" + str(y)) #print ("Predicted Output: \n" + str(NN.forward(X))) #print ("Loss: \n" + str(np.mean(np.square(y - NN.forward(X))))) # mean sum squared loss o = NN.forward(X) # print ("Actual Output: \n" + str(o)) largestValue = np.amax(o) print("Highest Value:" , largestValue) myaction,myreward = getAction() if myaction == "use 1": #place carpet_remaining = carpet_remaining - 1 print("*********** losing carpet ****************") print(carpet_remaining) 的乘法等效于['a'] * 4,因此也就是['a'] + ['a'] + ['a'] + ['a']

答案 2 :(得分:0)

  • 仔细考虑一下。
['a'] * 4 == ['a'] + ['a'] + ['a'] + ['a']
  • 添加两个列表应该给出列表。这是python定义的行为。
  • 如果你说的是真的,那么
['a'] + ['a'] = [['a'],['a']].
  • 这应该输出什么?
['a'] + ['a'] + ['a'] = [[['a'],['a']],['a']]  #??

['a'] + ['a'] + ['a'] + ['a'] = [[[['a'],['a']],['a']],['a']] # ?????????
(['a']*2)*3 #  what should be output of this?