简体   繁体   English

枚举用于在Python中查找元素的列表

[英]Enumeration of a list for finding elements in Python

In python how to iterate over list of elements and find if my required elements are present in the list or not. 在python中,如何遍历元素列表并查找列表中是否存在我所需的元素。

Then print if any one of those are found in the list, else say no elements found. 如果在列表中找到任何一个,则打印,否则说找不到任何元素。 (& Assert my code at the end ) (并在末尾声明我的代码)

I want to search and find for only mandatory 3 elements which are 'Name', 'Year' and 'City_id' from a list. 我想搜索并仅从列表中查找必需的3个元素,即“名称”,“年份”和“ City_id”。

And finally assert with foundcount so that test fails or passes. 最后使用foundcount进行断言,以使测试失败或通过。

Here is my code: 这是我的代码:

list = [ 'Name, 'Year', 'City_id', 'Region_Id' , 'Location', 'Source', 'Time']

reqVal = [ 'Name', 'Year', 'City_id' ] # items in List - if present or not
foundCount = 0

def isValInList():
    for reqVal in enumerate(list):
        if reqVal in list :
            print("Yes, %s required item is found in List : ", reqVal)
            foundCount += 1
        else:
            print('No required items are found in list')
            break


        assert (foundCount == 0)

isValInList()

So currently when I run this code, I get 所以目前,当我运行这段代码时,

No required items are found in list

Which is obviously wrong, can you please suggest and correct where I am doing it wrong. 这显然是错误的,请您提出建议并纠正我做错的地方。 thanks. 谢谢。

you could try: 您可以尝试:

my_list = ['Name', 'Year', 'City_id', 'Region_Id' , 'Location', 'Source', 'Time']
reqVal = ['Name', 'Year', 'City_id']

count_for_reqVal = {req_val : my_list.count(req_val) for req_val in reqVal}

print(count_for_reqVal)

#output : {'Name': 1, 'Year': 1, 'City_id': 1}

also, I was trying to reuse your code: 另外,我试图重用您的代码:

list = [ 'Name', 'Year', 'City_id', 'Region_Id' , 'Location', 'Source', 'Time']

reqVal = [ 'Name', 'Year', 'City_id', 'Test' ] # items in List - if present or not


def isValInList():
    foundCount = 0

    for val in reqVal:
        if val in list :
            print("Yes, '%s' required item is found in list" %  val)
            foundCount += 1

        else:
            print("No, '%s' required item is not in list" %  val)

    if foundCount == 0:
            print('No required items are found in list')



isValInList()

# output:
# Yes, 'Name' required item is found in list
# Yes, 'Year' required item is found in list
# Yes, 'City_id' required item is found in list
# No, 'Test' required item is not in list

Quite a lot going on: - Don't use predefined names like list as variable names - You need to pass your variables to the function - What is your assert good for? 发生了很多事情:-不要使用诸如list类的预定义名称作为变量名称-您需要将变量传递给函数-您的断言有什么用? - foundCount must be declared as global - enumerate generates a tuple - What is the break good for? -必须将foundCount声明为全局-枚举会生成一个元组-中断有什么用?

This works: 这有效:

alist = ['Name', 'Year', 'City_id', 'Region_Id' , 'Location', 'Source', 'Time']

reqVal = ['Name', 'Year', 'City_id' ] # items in List - if present or not

def isValInList(alist, blist):
    global foundCount
    for num, entry_a in enumerate(alist):
        if entry_a in blist :
            print("Yes, %s required item is found in List : ", entry_a)
            foundCount += 1
        else:
            print('No required items are found in list')

isValInList(alist, reqVal)

Using Set +info 使用Set +信息

list = { 'Name', 'Year', 'City_id', 'Region_Id' , 'Location', 'Source', 'Time'}

reqVal = { 'Name', 'Year', 'City_id' } # items in List - if present or not

def isValInList():
    assert True, reqVal.issubset(list)

isValInList()

Your question is not quite understandable.Be more specific.I wrote the answer as I understood your question. 您的问题不太容易理解。请更具体。我在理解您的问题的同时写下了答案。 list = [ 'Name, 'Year', 'City_id', 'Region_Id' , 'Location', 'Source', 'Time'] list = ['名称,'年份','City_id','Region_Id','位置','来源','时间']

reqVal = [ 'Name', 'Year', 'City_id' ] # items in List - if present or not
foundCount = 0

if 'Name' in list and 'Year' in list 'City_id' in list:
    print('All are present')

If we want to convert the list into an iterable list of tuples (or get the index based on a condition check, for example in linear search you might need to save the index of minimum element), you can use the enumerate() function. 如果我们要将列表转换为可迭代的元组列表(或基于条件检查获得索引,例如在线性搜索中,可能需要保存最小元素的索引),则可以使用enumerate()函数。

Example: 例:

# Python3 code to iterate over a list 
list = [1, 3, 5, 7, 9] 

# Using enumerate() 
for i, val in enumerate(list): 
    print (i, ",",val) 

Note : Even method #2 can be used to find the index, but method #1 can't (Unless an extra variable is incremented every iteration) and method #5 gives a concise representation of this indexing. 注意 :甚至方法2都可以用来找到索引,但是方法1不能(除非每次迭代都增加一个额外的变量),方法5给出了这种索引的简明表示。

You are iterating over the wrong list: 您正在遍历错误的列表:

for reqVal in enumerate(list):
    if reqVal in list :

try: 尝试:

for item in reqVal:
    if item in list:
        print("Yes, %s required item is found in List : ", element)
        foundCount += 1

    else:
        print('No required items are found in list')

This way there is no need for enumerate. 这样就无需枚举。 I don't see the point of breaking the loop before iterating over all the items. 我看不到遍历所有项目之前要中断循环的意义。

Furthermore, It is better not to use "list" as a var name for this is a key word in python. 此外,最好不要使用“ list”作为变量名,因为这是python中的关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM