如何将列表中的字符串转换为单个列表?

时间:2015-07-24 08:40:54

标签: python list

考虑一下,我有一个清单

subjects = ['subject1', 'subject2', 'subject3', 'subject4', 'subject5']

如何将这些单独的列表元素转换为单个列表?

subject1 = [ ]
subject2 = [ ]
subject3 = [ ]
subject4 = [ ]
subject5 = [ ] 

3 个答案:

答案 0 :(得分:4)

subjects = ['subject1', 'subject2', 'subject3', 'subject4', 'subject5']
ret = {}.fromkeys(subjects, [])

然后ret

{'subject1': [], 'subject2': [], 'subject3': [], 'subject4': [], 'subject5': []}

- 编辑 -

正如@Anand所说,所有值都是相同的列表引用。为避免这种情况,有一种解决方法:

ret = {k: [] for k in subjects}

答案 1 :(得分:0)

如果您使用词典,则可以执行以下操作:

MainActivity activity = (MainActivity) getActivity();
Object obj = activity.getData();
activity.setData(obj);

您可以通过执行以下操作来访问您的列表:

dictionnary = dict((s, []) for s in subjects)

答案 2 :(得分:0)

如果你真的想要个人名单,而不是字典:

for subject in subjects:
    exec(subject + " = list()")