1

リストを文字列に変換したいのですが、整数が含まれています。とにかくそれがコードです:

for player in basicPlayers:
  say('Name' + str(player['name']) + 'score' + str(player['score']))

そうそう、私はそれを好きにしたい

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
4

2 に答える 2

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 スコア 42、Name Joe スコア 24
于 2013-01-12T18:05:06.660 に答える
1

関数を使ったほうがいいformatと思います。

>>> basicPlayers = [{'name': 'John', 'score': 1}, {'name': 'Mary', 'score': 2}]
>>> ', '.join(('{name} ({score})'.format(**player) for player in basicPlayers))
'John (1), Mary (2)'
于 2013-01-12T18:19:05.967 に答える