python如何将值转换为列

时间:2017-09-08 23:32:33

标签: python-3.x

我有下面的python列表

<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.106</version>
</dependency>

我想把它变成类似

的东西
[[User1, LocationA, V1, V2, V3..],
 [User2, LocationB, V1,V2, V3..],
 [User3, LocationA, V1, V2, V3..],
 [User4, LocationC, V1, V2, V3..],
 [USer5, LocationC, V1, V2, V3..],
 [USer6, LocationD, V1, V2, V3..]] 

其中每个唯一位置由新的列表元素表示,其中1表示用户在该位置,0表示用户不在该位置。

我如何在python中执行此操作?

2 个答案:

答案 0 :(得分:0)

您可以使用将城市/位置映射到数字元组的字典,然后迭代原始数据,并使用星号运算符*解压缩城市名称和数字。

data = [
    ['User1', 'Seattle', 'V1', 'V2', 'V3'],
    ['User2', 'San Francisco', 'V1', 'V2', 'V3'],
    ['User3', 'New York', 'V1', 'V2', 'V3'],
    ['User4', 'Chicago', 'V1', 'V2', 'V3'],
    ]

# Create a dictionary that maps the cities to the numbers.
city_codes = {
    'Seattle': (1, 0, 0, 0),
    'San Francisco': (0, 1, 0, 0),
    'New York': (0, 0, 1, 0),
    'Chicago': (0, 0, 0, 1),
    }

# Create a new list.
changed_data = []
# Unpack the data.
for user, city, *rest in data:
    # Now append new sublists. Get the codes out of the dict
    # and unpack them into the list and also unpack the rest
    # of the list items. (You can only use multiple * asterisks
    # for the unpacking in Python 3.5 and above.)
    changed_data.append([user, *city_codes[city], *rest])


# Same as above as a nested list comprehension.
# changed_data = [[user, *city_codes[city], *rest]
#                 for user, city, *rest in data]

答案 1 :(得分:0)

这个怎么样:

l = [ ['User1', 'LocationA', 'V1', 'V2', 'V3'],
      ['User2', 'LocationB', 'V1', 'V2', 'V3'],
      ['User3', 'LocationA', 'V1', 'V2', 'V3'],
      ['User4', 'LocationC', 'V1', 'V2', 'V3'],
      ['USer5', 'LocationC', 'V1', 'V2', 'V3'],
      ['USer6', 'LocationD', 'V1', 'V2', 'V3'] ]

# get which index to set to '1' for locations in [0,0,0,0] 
indexes = [(ord(x[1][-1].lower())-96)-1 for x in l]

# new list default second element before setting '1'
idx1 = [0,0,0,0]

newl = []

for idx, subl in enumerate(l):
    idx1[indexes[idx]] = 1
    newl.append(l[idx])
    newl[idx][1] = ','.join([str(i) for i in idx1])
    idx1 = [0,0,0,0]

print newl

输出:

[['User1', '1,0,0,0', 'V1', 'V2', 'V3'], 
 ['User2', '0,1,0,0', 'V1', 'V2', 'V3'], 
 ['User3', '1,0,0,0', 'V1', 'V2', 'V3'], 
 ['User4', '0,0,1,0', 'V1', 'V2', 'V3'], 
 ['USer5', '0,0,1,0', 'V1', 'V2', 'V3'], 
 ['USer6', '0,0,0,1', 'V1', 'V2', 'V3']]