Take Matching Strings from List and Make New List

find string in list of strings python
python find string in list and return index
list comprehension || python
python check if string contains substring from list
python find index of string in list
python find similar strings in list
string match in list
for string in list python

So I have a long list of items and I need to make a new list for all the items that match. Here’s a simplified example:

Mylist = [cat, cat, dog, dog, bear, camel, camel, camel]

So I need to get to a point where:

Catlist = [cat,cat]

Doglist = [dog, dog]

Bearlist = [bear]

Camellist = [camel, camel, camel]

But the trick is the values in Mylist will change based on the dataset that is called in, so I’m never sure of what the contents are. I just have to make lists of the contents that match.

My original question was answered; however, I need to broaden the scope of my question just a bit. Let us say that I now have a matrix called animal_data which is composed of 4 columns: Animal, Xlocation, Ylocation, and Zlocation and that the first column contains the original MyList inputs and the remaining three have the gps locations of each animal in a field. How could I separate my matrix into chunks based on the type of animal? This is what I have so far:

setofthis = set(animal_data[:,0])

IDS = {

}

for one in setofthis:
    ids = [one for i in animal_data[:,0] if i == one]
    IDS.update({one:ids})

for one in result:
    print(one, ":", IDS[one])

The inputted data set is always changing so not all the same animals will appear in the set each time and different animals may also be added to the data set.

You could also use this simple piece of code with list comprehension

Mylist = ["cat", "cat", "dog", "dog", "bear", "camel", "camel", "camel"]
setofthis = set(Mylist)

result = {
}
for one in setofthis:
    res = [one for i in Mylist if i == one]
    result.update({one: res})

for one in result:
    print(one, " : ",result[one])

from this u will get something like this

dog  :  ['dog', 'dog']
bear  :  ['bear']
cat  :  ['cat', 'cat']
camel  :  ['camel', 'camel', 'camel']

Python, Let's discuss certain ways to find strings with given substring in list. Method #1 : Using to get string with substring. res = [i for i in It just filters out all the strings matching the particular substring and then adds it in a new list. filter_none. edit How is it possible to initialize (with a C# initializer) a list of strings? I have tried with the example below but it's not working. List<string> optionList = new List&lt;string&gt; { "

Mylist = ['cat', 'cat', 'dog', 'dog', 'bear', 'camel', 'camel', 'camel']
cats = []
dogs = []
camels = []

for item in Mylist:
    if item == 'cat':
        cats += [item]
    if item == 'dog':
        dogs += [item]
    if item == 'camel':
        camels += [item]

print(cats)
print(dogs)
print(camels)

Find a string in a List in Python, In this article, we'll take a look at how we can find a string in a list in Python. matches = [match for match in ls if "Hello" in match]. print (matches)  This is most generic method that strikes any programmer while performing this kind of operation. Just looping over whole list and convert each of the string of list to int by type casting.

Using individual variables for each list is not the way to go — especially since you don't know ahead of time what the data contains. You should use a data structure like a dictionary to make the data easy to work with and keep it in one place.

You can use itertools.groupby to turn your list into a dictionary of lists. The keys will be the animal and the values will be the list of animals. You will need to make sure the list is sorted so the identical animals are grouped together:

from itertools import groupby

Mylist = ['cat', 'dog', 'bear', 'camel', 'camel','cat', 'camel','dog']
animals = {k:list(g) for k, g in groupby(sorted(Mylist))}

Result animals:

{'bear': ['bear'],
 'camel': ['camel', 'camel', 'camel'],
 'cat': ['cat', 'cat'],
 'dog': ['dog', 'dog']}

From here you can get your individual lists by simply indexing into the dictionary:

print(animals['cat']) # ['cat', 'cat']

11. Lists, Lists and strings — and other collections that maintain the order of their items There are several ways to create a new list; the simplest is to enclose the If you try to access or assign to an element that does not exist, you get a runtime error:. MATCH locates items by looking for a count of zero (i.e. looking for items that do not yet appear in the unique list). This works, because MATCH always returns the first match when there are duplicates. Finally, the positions are fed into INDEX as row numbers, and INDEX returns the name at that position. Non array version with LOOKUP

9. Lists, There are several ways to create a new list; the simplest is to enclose the elements in Like numeric 0 values and the empty string, the empty list is false in a If you try to read or write an element that does not exist, you get a runtime error:. Create a Unique List in Excel based on Criteria. February 23, 2017. Nathan is working on a spreadsheet that contains a list of car models and owners. He needs to create a unique list of owners per car. “Maybe I can use an IF() formula,” he thinks to himself and decides to give it a go. However, after several failed attempts he decides to

[PDF] Lists and Pattern Matching, Pattern matching: an awesome feature not found Recursion! Functions over lists are usually recursive: only way to “get Instead, build up new lists out of old. Dim list As New List (Of String) list.Add ("spaniel") list.Add ("beagle") ' Insert a string into the list. list. Insert (1, "dalmatian") ' Loop through the entire list. For Each str As String In list Console.WriteLine (str) Next End Sub End Module Output spaniel dalmatian beagle

list, Reading list(LENGTH <list> <out-var>) list(GET <list> <element index> [<index> . may create new values for the list within the current CMake variable scope. b c d e) creates a list with a;b;c;d;e , and set(var "a b c d e") creates a string or a list In REGEX mode, items will be matched against the given regular expression. It is not possible to use the join() function on this list. We first have to convert each element to a string to form a new one, and then only we can call join() method. # Let's convert sourceList to a list of strings and then join its elements. stringList = ' '.join([str(item) for item in sourceList ]) The final string would appear something like:

Comments
  • Welcome to StackOverflow! Please edit your post to include the code you've already written in your solution attempts, as well as any other relevant info about your dataset or other factors.
  • Thank you! This was very helpful, but now I need to make it just a little more complicated to really get to the heart of my problem. Let us say that Mylist is composed of 4 columns: Animal, Xlocation, Ylocation, and Zlocation and that the first column contains the original MyList inputs and the remaining three have the gps locations of each animal in a field. How could I separate my large dataset into smaller sets based on the type of animal and containing the animal and its location?
  • without a specific input its hard to help you. In which data structure are the information animal,Xlocation,Ylocation,Zlocation currently stored? list of dicts?
  • if you have a list of dict like this: l = [ { 'animal' : 'cat', 'x': 2, 'y':4, 'z':1},{'animal...}] - list comprehension is still the easiest way, just try this: result = [record for record in data if record["animal"] == "cat"]. This gives you a list that contains only 'cat' records. Greetings
  • The data is an inputted text file from the user and is in array form with four columns and a changing number of rows. The rows change based on what file is inputted. I don’t know if I can use a dictionary because the type of animal that could be in the dataset is upwards of 200 items. I really just need to write something that will search my first column for animals that are the same and group each appearance of the animal with its location but everything I have tried isn’t working. (I guess I’m not the best programmer ha.) Thanks again for the support!
  • I think I did a much better job explaining my question here: stackoverflow.com/questions/58663133/… if you'd like to take a look.