我正在尝试检查列表列表中是否存在元素,如果是,请在此特定列表中执行某些操作(在列表列表中):
transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]
我想做以下事情:
## non-Python code
if ['John',x] exists in transactions:
## I need to have the index where [John,x] is at that point
then transactions[index][1] += transac1[1]
else:
transactions.append(['John',6])
因此,使用transac1执行此循环将使:
transactions = [['Marie',2],['Emma',9],['John',6]]
使用transac2执行此循环将使:
transactions = [['Marie',2],['Emma',15],['John',6]]
我遇到的“经典双循环”的问题是,每次它找不到['John',x]时它会附加到列表中,在做某事之前我需要知道整个列表(另外,我保证如果'John'在列表中,它只有一次)。
我的约束是我不能使用词典。非常感谢。
答案 0 :(得分:0)
循环遍历列表并获取索引:
for idx, item in enumerate(transactions):
if item[0] == 'John' and item[1] == x:
pass
else:
transactions.append(['John',6])
答案 1 :(得分:0)
使用numpy
选项吗?如果是这样,您可以执行以下操作:
import numpy as np
transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]
t1 = np.array(transac1)
t2 = np.array(transac2)
tt = np.array(transactions)
names = tt[:, 0]
amounts = tt[:, 1]
if t1[0] in names:
tt[names.index(t1[0]), 1] += t[1]
else:
tt.append([t1[0], t1[1])
如果没有,我会在每次迭代时检查名称。
transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]
# Run with transac1
def func():
for i, t in enumerate(transactions):
if t[0] == transac1[0]:
transactions[i][1] += transac1[1]
return transactions
transactions.append([transac1[0], transac1[1])
return transactions
func()