我想将列表转换为字符串,但它包含整数。它现在有效,无论如何这是代码:
for player in basicPlayers:
say('Name' + str(player['name']) + 'score' + str(player['score']))
Sooo是的,我想让它像
Player1 (2), Player2 (4), Player3 (6)
不是
Player1 (2)
Player2 (4)
Player3 (6)
获取数据的代码:
def getBasicPlayers(self): # Finished
"""Returns a list containing a dictionary for each player:
[
{
'name' : string,
'score' : integer,
},
{
'name' : string,
'score' : integer,
},
]
Note: This will return an empty list if the player count is above 100."""
packet = self.assemblePacket("c")
self.send(packet)
reply = self.receive()
reply = reply[11:] # Clean up bytes
players = []
strLen = struct.unpack("<h", reply[0:2])
playerCount = strLen[0]
reply = reply[2:] # Clean up bytes
for i in range(playerCount):
players.append({'name' : '', 'score' : 0})
pointer = 0
for player in players:
strLen = ord(reply[pointer:(pointer + 1)])
name = reply[(pointer + 1):(pointer + (strLen + 1))]
temp = struct.unpack("<i", reply[(pointer + (strLen + 1)):(pointer + (strLen + 5))])
pointer += (strLen + 5)
player['name'] = name
player['score'] = temp[0]
return players
答案 0 :(得分:2)
怎么样
', '.join('Name %(name)s Score %(score)d' % player for player in basicPlayers)
请注意join
将 iterable 作为参数,在这种情况下,我们将生成器表达式传递给它。
例如:
basicPlayers = [{'name' : 'Bob','score' : 42}, {'name' : 'Joe','score' : 24}]
print ', '.join('Name %(name)s Score %(score)d' %
player for player in basicPlayers)
Name Bob Score 42, Name Joe Score 24
答案 1 :(得分:1)
我认为最好使用format
功能。
>>> basicPlayers = [{'name': 'John', 'score': 1}, {'name': 'Mary', 'score': 2}]
>>> ', '.join(('{name} ({score})'.format(**player) for player in basicPlayers))
'John (1), Mary (2)'