Python从多个列表附加到标签

2024-09-24 22:31:24 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有几个列表,它们是数据文件中变量的标题。设置如下所示:

headerGroup1 = ["1", "2", "3, "4", "5"]
headerGroup2 = ["6", "7", "8, "9", "10"]
headerGroup3 = ["1", "2", "3", "4", "5"]

我有一个主文件如下:

masterVars = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

我想做三件事:

  • 创建一个列表,按顺序包含masterVars中的所有项。我不知道价值是否是唯一的。在
  • 如果headerGroupX中包含的列表项在masterVars中,请将该头组前置到列表项。在
  • 将包含所有64k项的列表转储到我可以在SPSS中管理的内容中(这有点开玩笑)

我想如果只有两张单子的话,这会很简单。我想我遇到的一个大问题是,在将数据预先添加到列表项之后会发生什么。但我不太清楚我到底搞砸了什么。在

编辑时间:

下面是我想要输出的示例:

newMasterFile = ["headerGroup1, headerGroup3, 1", "headerGroup1, headerGroup3, 2", etc.]

这有什么更清楚的吗?在


Tags: 文件标题内容列表顺序数据文件单子价值
2条回答

Create a list that includes all the items from masterVars in order. And I don't know if values are unique.

它已经“排序”(引用引号,因为你从来没有解释过你想要什么顺序),但是假设它不是:

>>> shuffle(masterVars)
>>> masterVars ['2', '9', '5', '7', '4', '1', '10', '6', '8', '3']
>>> sort(masterVars, key=lambda x: int(x))
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

如果不知道值是否唯一,并且希望它们唯一,请将其转换为set。在

If a list item contained in headerGroupX is in the masterVars, prepend that header group to the list item.

^{pr2}$
import functools # python3 compatibility (for reduce function)

# unsorted - see 3,4 are swaped!
masterVars = ["1", "2", "4", "3", "5", "6", "7", "8", "9", "10"]

input_dict=dict(headerGroup1 = ["1", "2", "3", "4", "5"],headerGroup2 = ["6", "7", "8", "9", "10"],headerGroup3 = ["1", "2", "3", "4", "5"])

# used builtins sorted function for sorting 
new_master_file=[' '.join(j[0])+' '+j[1] for j in [functools.reduce(lambda a,b:(i in input_dict[b] and a[0]+[b] or a[0],i),input_dict,[[],i]) for i in sorted(masterVars,key=int)]]

for i in new_master_file:
    print (i)

或者你喜欢更易读的版本?;)

什么是SPSS?在

相关问题 更多 >