【发布时间】:2015-05-28 23:10:23
【问题描述】:
我有两个具有以下结构的表,在表 1 中,ID 位于名称旁边,而在表 2 中,ID 位于标题 1 旁边。两个表之间的一个相似之处是,第一个人总是有他们名字旁边的 ID。对于后来的人来说,他们是不同的。
表一:
Name&Title | ID #
----------------------
Random_Name 1|2000
Title_1_1 | -
Title_1_2 | -
Random_Name 2| 2000
Title_2_1 | -
Title_2_2 | -
... |...
表 2:
Name&Title | ID #
----------------------
Random_Name 1| 2000
Title_1_1 | -
Title_1_2 | -
Random_Name 2| -
Title_2_1 | 2000
Title_2_2 | -
... |...
我有识别表 1 的代码,但很难合并结构 2。该表存储为嵌套的行列表(每一行都是一个列表)。通常,一个人只有 1 行姓名,但有多行标题。伪代码是这样的:
set count = 0
find the ID next to the first name, set it to be a recognizer
for row_i,row in enumerate(table):
compare the ID of the next row until I found: row[1] == recognizer
set count = row i
slice the table to get the first person.
实际代码是这样的:
header_ind = 0 # something related to the rest of the code
recognizer = data[header_ind+1][1]
count = header_ind+1
result = []
result.append(data[0]) #this append the headers
for i, row in enumerate(data[header_ind+2:]):
if i <= len(data[header_ind+4:]):
if row[1] and data[i+1+header_ind+2][1] is recognizer:
print data[i+header_ind+3]
one_person = data[count:i+header_ind+3]
result.append(one_person)
count = i+header_ind+3
else:
if i == len(data[header_ind+3:]):
last_person = data[count:i+header_ind+3]
result.append(last_person)
count = i+header_ind+3
我一直在考虑这个问题,所以我只想知道是否有可能得到一个算法来合并表 2,因为我们无法区分行名和标题。
【问题讨论】:
-
你是用字典做table1吗?如果是这样,您可以将此循环内的 table2 创建为将
i和row连接在一起的元素列表。 -
你的算法没有任何意义。目前尚不清楚该算法正在尝试做什么。什么是“识别器”?无论如何,您为什么不能简单地遍历表格两次(每列一次),丢弃不相关的条目并将名称挑选到单独的列表中?
-
@SebasSBM 我不认为我理解你的方法。但我可以将它创建为字典。假设我想找到 Random_Name 1 行的索引
i和 Random_Name 2 行的索引i。它是如何工作的? -
@aestrivex 由于许多原因,我无法分别识别名称和标题。例如,如果我通过 table2 并丢弃 column ID 中的所有空条目,我将丢失 Random_Name 2。而且,recognizer 是原始 ID(类似于性别或出生年份)。这两个表中的每个人都将具有相同的 ID。但是,它被保存在不同的行中。
-
你为什么会“丢失”空条目?问题是否还伴随着您不能多次遍历数组的约束?如果有,为什么?
标签: python algorithm data-structures