[英]Python: List of lists - presence of an element
I am trying to check the presence of an element in a list of lists and, if so, do something at this particular list (within the list of list): 我正在尝试检查列表列表中元素的存在,如果是,请在此特定列表(列表列表内)中执行以下操作:
transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]
I would like to do the following: 我要执行以下操作:
## 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])
So executing this loop with transac1 would make: 因此,使用transac1执行此循环将使:
transactions = [['Marie',2],['Emma',9],['John',6]]
And executing this loop with transac2 would make: 而使用transac2执行此循环将使:
transactions = [['Marie',2],['Emma',15],['John',6]]
The problem I face with a "classic double loop" is that, each time it does not find ['John',x] it will append to the list, where I need to know that for the entire list before doing something (plus, I have the assurance that if 'John' is in the list, it is only once). 我面对的“经典双循环”问题是,每次找不到['John',x]时,它都会追加到列表中,在执行某件事之前,我需要知道整个列表(再加上,我可以保证,如果“ John”在列表中,则只有一次)。
My constraint is I cannot use Dictionaries. 我的约束是我不能使用字典。 Thanks a lot.
非常感谢。
To loop over the list of list and get the indexes: 要遍历列表列表并获取索引:
for idx, item in enumerate(transactions):
if item[0] == 'John' and item[1] == x:
pass
else:
transactions.append(['John',6])
Is using numpy
an option? 是否使用
numpy
选项? If so, you can do the following: 如果是这样,您可以执行以下操作:
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])
If not, I would just check the name every iteration. 如果没有,我将在每次迭代时检查名称。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.