我在检查一列中的列表元素是否与另一列中的元素匹配时遇到一些问题。
具体地说,我有一个这样的数据集:
Student Student representatives
Mary Jane [Mary Jane, Lucas]
Christopher [Matt]
Jonathan [Luke]
Barbara [Barbara, Martin]
我应该做的是选择每一行并与学生代表核对学生的价值。如果它们匹配,我应该从数组中删除该元素。
预期输出:
Student Student representatives
Mary Jane [Lucas]
Christopher [Matt]
Jonathan [Luke]
Barbara [Martin]
您能给我一些建议吗?谢谢。
答案 0 :(得分:1)
这是新手的工作内容-希望对您有所帮助---以为我同意这不是最佳解决方案...
说
student = ['Mary Jane', 'Christopher', 'Jonathan', 'Barbara']
student_rep = [['Mary Jane', 'Lucas'], ['Matt'], ['Luke'], ['Barbara', 'Martin']]
student_rep_new = []
for i in range(len(student)):
test = []
for j in range(len(student_rep[i])):
if student_rep[i][j] != student[i]:
test.append(student_rep[i][j])
# student_rep_new.append([student_rep[i][j]])
student_rep_new.append(test)
print(student)
print(student_rep)
print(student_rep_new)
输入:
['Mary Jane','Christopher','Jonathan','Barbara']
和
[['Mary Jane','Lucas'],['Matt'],['Luke'],['Barbara','Martin']]
输出:
[['Lucas'],['Matt'],['Luke'],['Martin']]
答案 1 :(得分:1)
如果您使用的是pandas dataframe
,
import pandas as pd
df = pd.DataFrame({
"stu": ['Mary Jane', 'Christopher', 'Jonathan', 'Barbara'],
"stu_rep": [['Mary Jane', 'Lucas'], ['Matt'], ['Luke'], ['Barbara', 'Martin']],
})
df.assign(
stu_rep = df.apply(lambda x: [s for s in x['stu_rep'] if s != x['stu']], axis=1)
)
stu stu_rep
0 Mary Jane [Lucas]
1 Christopher [Matt]
2 Jonathan [Luke]
3 Barbara [Martin]
答案 2 :(得分:0)
将数据保存为字典。然后就很简单。
dictNames = {'Mary Jane':['Mary Jane','Lucas'] , 'Christopher': ['Matt'],'Jonathan':['Luke'],'Barbara': ['Barbara', 'Martin']}
for k,v in dictNames.items():
dictNames[k] = [x for x in v if x != k]
print(dictNames)