将列表转换为行

时间:2016-07-28 15:28:58

标签: python list

在python中将列表转换为单独元素的有效方法是什么?

我有一个看起来像这样的数据集;

['StudentA','80','94','93']
['StudentB','93','94']

我想重塑数据,以便每个学生/分数都有自己的行;

['StudentA','80']
['StudentA','94']
etc...

5 个答案:

答案 0 :(得分:3)

您可以使用列表推导,如下所示:

data = ['StudentA','80','94','93']
res = [[data[0], x] for x in data[1:]]

这会将res设置为[['StudentA', '80'], ['StudentA', '94'], ['StudentA', '93']]

答案 1 :(得分:1)

    c=['StudentA','80','94','93']

    d=[[c[0], p] for p in c[1:]]

答案 2 :(得分:0)

如果它是包含这些行的列表(all_students),您可以通过执行以下操作来执行所需操作:

result = []
for student in all_students:
    student_name = student[0]
    result.extend([[student_name, value] for value in student[1:]]
print(result)

答案 3 :(得分:0)

使用dictionary学生与相应的数据结合在一起。

def to_dict(l):
    d = {}
    for i in l:
        key = i[0]
        value = i[1:]
        d[key] = value
    return d    

示例输出:

l = [['studentA', 90, 90],['studentB', 78, 40]]
print to_dict(l)
>>> {'studentB': [78, 40], 'studentA': [90, 90]}
for key, value in d.iteritems():
    for i in value:
        print key, i
>>> studentB 78
>>> studentB 40
>>> studentA 90
>>> studentA 90

答案 4 :(得分:0)

此词典理解将按学生姓名对数据进行分组:

d = {x[0]: x[1:] for x in dataset}

即:

>>> d
{'StudentA': ['80', '94', '93'], 'StudentB': ['93', '94']}

您可以使用嵌套for循环或列表推导来提取单个对:

>>> [(k, w) for k, v in d.items() for w in v]
[('StudentA', '80'), ('StudentA', '94'), ('StudentA', '93'), ('StudentB', '93'), ('StudentB', '94')]