简体   繁体   中英

Checking if an element in first list of strings occurs in second list of strings

I apologise if there are dupes: I've tried looking for similar questions but no luck:( Let's say my code is like the following:

buckets = []
A = ["apple", "pear", "orange"]
B = ["pear"]

for a in A:
    if a in B:
        buckets.append(A[a])

so since pear from A occurs in B, I'd like to append "pear" to my list to show that "pear" is in list A and has occurred in list B. However I'm getting an error saying

TypeError: list indices must be integers or slices, not str

The question seems really trivial but I can't seem to find the bug. Any help would be appreciated!

EDIT: it was such a small fix. So sorry for such a redundant-looking question. Thanks for answering!

Here A[a] you are trying to get element using the element itself. for a in A produces items, not indexes.

The fix is simple:

buckets.append(a)

And actually this could have been achieved easier:

buckets = list(set(A).intersection(B))

You iterate through words of the list, not through indexes. Meaning you're indexing a list type with a string, which is not as list-type works. A quick fix would be:

for a in A:
    if a in B:
        buckets.append(a)

You are on the right track. Just your append statement is incorrect. Do this

buckets = []
A = ["apple", "pear", "orange"]
B = ["pear"]

for a in A:
    if a in B:
        buckets.append(a)

A pythonic way is using list comprehension:

buckets =[i for i in A if i in B]

I think this should work fine

buckets = []
A = ["apple", "pear", "orange"]
B = ["pear"]

for a in A:
    if a in B:
        buckets.append(a)
    buckets = []
    A = ["apple", "pear", "orange"]
    B = ["pear"]

    for a in A:
        if a in B:
            buckets.append(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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