Python Forum
Create a new list by comparing values in a list and string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create a new list by comparing values in a list and string
#1
Hello,

I have elements in a predefined list and a query string.  I would like to check if the query_str has any values in predefined list and if so, append them to a new list as separate elements.

predefined_lst = ['hello', 'goodbye', 'see you later']
query_str  = 'hello | are you having a nice day?  see you later |'
new_lst = [ ]
I have the syntax to compare the string to the values in the list, but I can't get the values that appear in the string to append to the new list as individual elements in the list.
In the example above, new_lst should be
new_lst = ['hello', 'see you later']
What I have now just results in True when I print new_lst.  Thanks for any help


new_list = []
match = if any(string in query_str for string in predefined_lst)
new_lst.append(match)
print(new_lst)
Reply
#2
tips
1. any return true or false.
this is a true and false statement.
string in query_str
so if you remove if any.
it returns a generator of true and false
(string in query_str for string in predefined_lst)
2. write it out long hand. avoid the expression.
99 percent of computer problems exists between chair and keyboard.
Reply
#3
predefined_lst = ['hello', 'goodbye', 'see you later']
query_str = 'hello | are you having a nice day?  see you later |'
new_lst = [string for string in predefined_lst if string in query_str]
print(new_lst)
Output:
['hello', 'see you later']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to parse and group hierarchical list items from an unindented string in Python? ann23fr 0 77 Yesterday, 01:16 PM
Last Post: ann23fr
  Copying the order of another list with identical values gohanhango 7 1,060 Nov-29-2023, 09:17 PM
Last Post: Pedroski55
  Comparing Dataframe to String? RockBlok 2 363 Nov-24-2023, 04:55 PM
Last Post: RockBlok
  Sample random, unique string pairs from a list without repetitions walterwhite 1 401 Nov-19-2023, 10:07 PM
Last Post: deanhystad
  Search Excel File with a list of values huzzug 4 1,147 Nov-03-2023, 05:35 PM
Last Post: huzzug
  trouble reading string/module from excel as a list popular_dog 0 384 Oct-04-2023, 01:07 PM
Last Post: popular_dog
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,091 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  String to List question help James_Thomas 6 921 Sep-06-2023, 02:32 PM
Last Post: deanhystad
  Trying to compare string values in an if statement israelsattleen 1 519 Jul-08-2023, 03:49 PM
Last Post: deanhystad
  Comparing List values to get indexes Edward_ 7 1,082 Jun-09-2023, 04:57 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020