I have a list as following:
list12 = ['**FIRS0425 SOPL ZTE First Company limited', 'Apple Technology','*ROS Sami']
My code is as following
import re
[item2 for item in list12 for item2 in item.split() if not re.match("^[*A-Z]+(0-9){4}$", item2)]
I got output like :
['First', 'Company', 'limited', 'Apple', 'Technology', 'Sami']
I expect the output to be like :
['SOPL', 'ZTE', 'First', 'Company', 'limited', 'Apple', 'Technology', 'ROS', 'Sami']
I am not good with regular expression. How can I reach to my required solution?
A non-regex way in python,
list12 = ['**FIRS0425 SOPL ZTE First Company limited', 'Apple Technology','*ROS Sami']
str = " ".join(list12)
list21 = str.split()
res = [k.strip('*') for k in list21 if '**' not in k]
print(res)
Output:
['SOPL', 'ZTE', 'First', 'Company', 'limited', 'Apple', 'Technology', 'ROS', 'Sami']
DEMO: http://tpcg.io/s9aBhe
Seems you're looking for
\b([A-Za-z]+)\b
In Python:
import re
list12 = ['**FIRS0425 SOPL ZTE First Company limited', 'Apple Technology','*ROS Sami']
rx = re.compile(r'\b([A-Za-z]+)\b')
result = [word for item in list12 for word in rx.findall(item)]
print(result)
Which yields
['SOPL', 'ZTE', 'First', 'Company', 'limited', 'Apple', 'Technology', 'ROS', 'Sami']
Related
I have multiple empty lists and dict in side list. I need to extract dict key values in list.
Example:
l =([{'COUNTRY': 'UK', 'STUDENT': 'JOHN'}, {'COUNTRY': 'PT', 'STUDENT':'PEDRO'}, {'COUNTRY': 'UK', 'STUDENT': 'KYLE'}, {'COUNTRY': 'IT', 'STUDENT':'PIRLO'}, {'COUNTRY': 'PT', 'STUDENT':'ANA'}, {'COUNTRY': 'FR', 'STUDENT':'VITO'}, {'COUNTRY': 'FR', 'STUDENT':'LOUIS'}, [], []])
expected result:
k = ['UK', 'PT', 'UK', 'IT', 'PT', 'FR', 'FR']
Hello i try to get the tags attribute
i have this
def treeview(self):
w = self.widget
curItem = w.focus()
print w.item(curItem)
lisswidget = ttk.Treeview(photoFrame)
lisswidget.bind("<<TreeviewSelect>>", treeview)
lisswidget.insert('', 'end', "", open=True, image=IMG, tags="MyTags")
The console return :
{'text': '', 'image': [u'pyimage9'], 'values': '', 'open': 1, 'tags': ['MyTags']}
How i can extract tags ?
Thx
I find it, it's a dictionnary so i do like this :
print w.item(curItem)['tags']
Is there any nice pythonic way of merging dictionaries within a list?
What I have:
[
{ 'name': "Jack" },
{ 'age': "28" }
]
What I would like:
[
{ 'name': "Jack", 'age': "28" }
]
Here's a method that uses dict.update(). In my opinion it's a very readable solution:
data = [{'name': 'Jack'}, {'age': '28'}]
new_dict = {}
for d in data:
new_dict.update(d)
new_data = [new_dict]
print new_data
OUTPUT
[{'age': '28', 'name': 'Jack'}]
If you're using Python 3, you can use collections.ChainMap:
>>> from collections import ChainMap
>>> ld = [
... { 'name': "Jack" },
... { 'age': "28" }
... ]
>>> [dict(ChainMap(*ld))]
[{'name': 'Jack', 'age': '28'}]
You could use list comprehension:
final_list = [{key: one_dict[key]
for one_dict in initial_list
for key in one_dict.keys()}]
Edit: the list comprehension was backwards
out = reduce(lambda one, two: dict(one.items() + two.items()),
[{'name': 'Jack'}, {'age': '28'}, {'last_name': 'Daniels'}])
print(out)
OUTPUT
{'age': '28', 'last_name': 'Daniels', 'name': 'Jack'}
I have a list:
txtlst = [
['000001', 'DOE', 'JOHN', 'COMSCI', '', 'MATH', '', 'ENGLISH\n'],
['000002', 'DOE', 'JANE', 'FRENCH', '', 'MUSIC', '', 'COMSCI\n']
]
And I want to put the elements in a dictionary so it looks likes this
mydict = {
'000001': ['000001', 'DOE', 'JOHN', 'COMSCI', '', 'MATH', '', 'ENGLISH\n'],
'000002': ['000002', 'DOE', 'JANE', 'FRENCH', '', 'MUSIC', '', 'COMSCI\n']
}
My problem here is, after I ran the code
for i in txtlst:
key = i[0]
value = i
mydict = {key:value}
The two sublists of txtlst are added to different dictionaries. How can I fix my code so they will be in the same dictionary as I mentioned above?
You can easily create a new dictionary with the first element of each list as key:
mydict = { i[0]: i for i in txtlst }
If you wish to do that in a loop like in your approach, you need to initialize a dictionary beforehand and update it in each iteration:
mydict = {}
for i in txtlst:
key = i[0]
value = i
mydict[key] = value
I am new to Elixir and still very confused with pattern matching.
[%{name: "Deutschland", code: "DE"}, %{name: "Frankreich", code: "FR"}]
def find_by_code([], _name), do: []
def find_by_code([h | t], query) do
if h[:code] == query do
IO.puts("MATCH")
IO.inspect(h)
else
IO.puts ("No match")
find_by_code(t, query)
end
end
Is that the best way to find the country by code?
You can pattern match as deep as you want:
def find_by_code([], _query),
do: nil # or whatever you want to mean "not found"
def find_by_code([%{code: query} = country|_t], query),
do: IO.inspect(country)
def find_by_code([_country|t], query),
do: find_by_code(t, query)
You can also use the Enum.find/3 with match?/2, which may be more readable (as suggested in another answer).
You could do it this way:
countries = [
%{name: "Deutschland", code: "DE"},
%{name: "Frankreich", code: "FR"}
]
Enum.find(countries, &match?(%{code: "FR"}, &1))
# %{code: "FR", name: "Frankreich"}
Elixir doesn't have built in pattern matching for trying to filter out certain items of a list based on their values.
You could write a pattern match to check individual items like so:
match_country_code = fn (%{:code => "DE"} = country) -> country
(_) -> nil
end
And then pass that to Enum.find:
lands = [
%{name: "Deutschland", code: "DE"},
%{name: "Frankreich", code: "FR"}
]
Enum.find(lands, &(match_country_code.(&1)))
# => %{code: "DE", name: "Deutschland"}
Or to generalize you could:
lands = [
%{name: "Deutschland", code: "DE"},
%{name: "Frankreich", code: "FR"}
]
find_by = fn (list, key, val) ->
Enum.find(list, &(Map.get(&1, key)==val))
end
find_by.(lands, :name, "DE")
#=> %{code: "DE", name: "Deutschland"}
Change find to filter and get a list of results:
lands = [
%{name: "Deutschland", code: "DE"},
%{name: "Germany", code: "DE"},
%{name: "Frankreich", code: "FR"}
]
filter_by = fn (list, key, val) ->
Enum.filter(list, &(Map.get(&1, key)==val))
end
filter_by.(lands, :code, "DE")
#=> [%{code: "DE", name: "Deutschland"}, %{code: "DE", name: "Germany"}]