简体   繁体   中英

How can I find elements in a list that have same value in Python?

My question is how can I find strings in a list that have the same number of characters if my list is...

myList = ["Hello", "How","are", "you"]

and I want it to return the strings that are of value 3

example from above list...

["How","are","you"]

This is what I've tried...

def listNum(myList, x):
    for i in range(len(myList)):
        if i == x:
            return(i)



myList = ["Hello", "How","are", "you"]
x = 3
listNum(myList, x)

Your function is off because you are comparing the list index to the value you are trying to match with i == x . You want to use myList[i] == x . But it seems you actually want to check the length, so len(myList[i]) == x .

However, I prefer iterating over the actual elements in a loop (or list comprehension as noted in comments by Joran Beasley). You also mentioned that you wanted to check if for string of certain length, so you can also add a check for the object type:

def listNum(myList, x):
    return [item for item in myList if type(item) is str and len(item) == x]

Use the setdefault() method. This solution should give you a dictionary of all the word lengths mapped to their respective words

CODE

myList = ["Hello", "How","are", "you"]

dict1 = {}
for ele in myList:
    key = len(ele)
    dict1.setdefault(key, [])
    dict1[key].append(ele)

OUTPUT

I guess this is the output you are trying to achieve.

>>> print(dict1)
{5: ['Hello'], 3: ['How', 'are', 'you']}

You can use this to query the dictionary and get the words corresponding to their word lengths. For eg dict1[5] would return 'hello'

If you are planning to use it for further enhancement i suggest you make dict in one loop then you can easily retrieve that for any number of characters. if you search for x=3 or 4 each time you have to go through your list. rather then that make dict with one loop.

myList = ["Hello", "How","are", "you"]

data = {}
for i in myList:
    if len(i) in data:
        data[len(i)].append(i)
    else:
        data[len(i)] = [i]

# print(data)

x = 3
print(data[x])

output:

['How', 'are', 'you']

I believe you can use Python filter function here.

# list
myList = ["Hello", "How","are", "you"]

# function that examines each element in an array and returns it if True
def filterData(item):
    if(len(item) == 3):
        return True
    else:
        return False

# filter function that takes 'function-to-run' and an array
filtered = filter(filterData, myList)

# result
print('The filtered strings are:')
for item in filtered:
    print(item)

Hope it helped. Cheers!

You can use the function groupby() with a sorted list:

from itertools import groupby

myList = ["Hello", "How", "are", "you"]

f = lambda x: len(x)
l = sorted(myList, key=f)
r = {k: list(g) for k, g in groupby(l, key=f)}
# {3: ['How', 'are', 'you'], 5: ['Hello']}
r[3]
# ['How', 'are', 'you']

Try this code.

Code

def func_same_length(array,index):
    res = [array[i] for i in range(0,len(array)) if len(array[index]) == len(array[i]) and i!=index]
    return res



myList = ["Hello", "How", "are", "you"]
resSet = set()
for index in range(0,len(myList)):
    res = func_same_length(myList,index)
    for i in res:
        resSet.add(i)

print(resSet)

Output

{'How', 'are', 'you'}

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