如果我有不同长度的多个列表,那么是否有一种简单的方法对所有这些列表进行相同的迭代。
所以写了这样的东西:
for item in list1:
function(item)
for item in list2:
function(item)
.
.
.
for item in listn:
function(item)
我只是写了这样的东西:
for item in list1,list2,...,listn:
function(item)
我知道你可以通过组合列表来做到这一点--我想要的比每次调用函数时组合它们更有效率
假设我在Python中有这段代码。我是一个Perl程序员,正如您可能知道的那样。
# Both list1 and list2 are a list of strings
for x in list1:
for y in list2:
if y in x:
return True
return False
还有什么更好的方法来处理这件事?我认为一个列表理解可以做得很好,但我无法理解其中的“处理两个单独的列表”部分。
我有两份名单:
list1 = ["a","b","c","d"]
list2 = ["e","f","g","a"]
我想确保他们没有任何共同点。如果是这样,我想从这两个列表中删除这些元素。因此,在这个例子中,应该从两个列表中删除"a“。
我试过使用列表理解:
list1 = [x for x in list1 if x not in list2]
list2 = [x for x in list2 if x not in list1]
打印列表将返回以下内
我有一份名单
list1 = [['a','b','c'],['m','n','o'],['x','y','z']]
现在,我想检查这些“子列表”中的所有元素是否都存在于一个名为list2的传入列表中。
例如,如果
list2 = ['a','c','e','b'] #Code would return True as a,b,c all from list1[0] match
list2
有没有一种聪明的方法可以在Python语言中遍历两个列表(不使用列表理解)?
我的意思是,就像这样:
# (a, b) is the cartesian product between the two lists' elements
for a, b in list1, list2:
foo(a, b)
而不是:
for a in list1:
for b in list2:
foo(a, b)
我有两个列表,我想在一个条件中使用list2的元素来检查list1中的元素。
list1 = ['antxyz', 'bear456', 'catabc', 'dog0xy', 'zebraayc']
list2 = ['cat', 'dog']
我的原始代码是这样工作的:
all('cat' in item or 'dog' in item for item in list2)
True
any('cat' in item or &
我有两个列表:list1和list2:
list1 = [4, 3, 20, 10]
list2 = ['a', 'f', 'd', 'b']
我想要创建一个新的列表result,条件是如果我的条件num==10是True,那么result应该保存来自list1的内容,否则它应该保存来自list2的内容。下面是我尝试过的代码:
num = 10
result = [element for element in list1 if num == 10 else list2]
但这提高了SyntaxError。我该如何做到这一点?
上述
我有两个列表:
var list1 = new List<string> { "A", "A", "B", C" };
var list2 = new List<string> { "A", "B" };
我想列出一个列表,像这样
var result = new[] { "A", "C" };
列表是从list1中删除的所有元素,从list2中删除,我不认为有Linq扩展方法,因为Except删除了重复的元素。
非linq的方法是:
var temp
我有两份名单
list1 = ['B', 'C', 'D']
list2 = [['1', 'A'], ['2', 'B'], ['3', 'D'], ['5', 'C']]
并希望返回包含list2元素的list1子列表。到目前为止,我尝试使用任何:
result = []
for l2 in list2:
if any (item in l2 for item in list1):
resu
我做这个有困难,我想做一个这样的函数:我有两个列表:list1 = [8,6,0] and list2 = [6,0]。我想保留两个列表之间相同的第一个值(这里是6)。比如,如果我有list1 = a,b,c和list2 = b,c。我只想保留值b。
def listFirstValue (list1,list2) :
for x in list1 :
for y in list2 :
if x == y :
break
break
return a
感谢您的回复。