This question already has answers here:
Find first sequence item that matches a criterion [duplicate]
(2 answers)
Closed 7 years ago.
I have a list that looks like
[{'name': 'red', 'test':4},... {'name': 'reded', 'test':44}]`
I have a name (for example: reded) and I want to find the dictionary in the list above that has name in the dictionary set to reded. What is a concise way of doing so?
My attempts look something similar to
x = [dict_elem for dict_elem in list_above if dict_elem['name']==reded]
Then I do
final_val = x[0]
if the name gets matched. This can also be done with a for loop but it just seems like there is a simple one-liner for this. Am I missing something?
You're pretty much there. If you use a generator- rather than list-comprehension, you can then pass it to next, which takes the first item.
try:
x = next(dict_elem for dict_elem in list_above if dict_elem['name'] == reded)
except StopIteration:
print "No match found"
Or
x = next((dict_elem for dict_elem in list_above if dict_elem['name'] == reded), None)
if not x:
print "No match found"
Related
This question already has answers here:
How to convert list to string [duplicate]
(3 answers)
Closed 2 years ago.
Here is my list ['k:1','d:2','k:3','z:0'] now I want to remove apostrophes from list item and store it in the string form like 'k:1 , d:2, k:3, z:0' Here is my code
nlist = ['k:1','d:2','k:3','z:0']
newlist = []
for x in nlist:
kk = x.strip("'")
newlist.append(kk)
This code still give me the same thing
Just do this : print(', '.join(['k:1','d:2','k:3','z:0']))
if you want to see them without the apostrophes, try to print one of them alone.
try this:
print(nlist[0])
output: k:1
you can see that apostrophes because it's inside a list, when you call the value alone the text comes clean.
I would recommend studying more about strings, it's very fundamental to know how they work.
The parenthesis comes from the way of representing a list, to know wether an element is a string or not, quotes are used
print(['aStr', False, 5]) # ['aStr', False, 5]
To pass from ['k:1','d:2','k:3','z:0'] to k:1 , d:2, k:3, z:0 you need to join the elements.
values = ['k:1','d:2','k:3','z:0']
value = ", ".join(values)
print(value) # k:1, d:2, k:3, z:0
What you have is a list of strings and you want to join them into a single string.
This can be done with ", ".join(['k:1','d:2','k:3','z:0']).
This question already has answers here:
What is getattr() exactly and how do I use it?
(14 answers)
How can I select a variable by (string) name?
(5 answers)
Closed 6 years ago.
I need to check variables looking like this:
if name1 != "":
(do something)
Where the number right after "name" is incremented between 1 and 10.
Do I need to write the test ten times or is there a way (without using an array or a dict) to "concatenate", so to speak, variable names?
I'm thinking about something like this:
for i in range(10):
if "name" + str(i) != "":
(do something)
Edit: I can't use a list because I'm actually trying to parse results from a Flask WTF form, where results are retrieved like this:
print(form.name1.data)
print(form.name2.data)
print(form.name3.data)
etc.
Use a list, such as:
names = ['bob', 'alice', 'john']
And then iterate on the list:
for n in names:
if n != "":
(do something)
or you could have a compounded if statement:
if (name1 != "" or name2 != "" or name3 != "")
The best solution would be to use solution #1.
If you cannot use a list or a dict, you could use eval
for i in range(10):
if eval("name" + str(i)) != "":
(do something)
First of all, your app have invalid logic. You should use list, dict or your custom obj.
You can get all variable in globals. Globals is a dict.
You can do next:
for i in range(10):
if globals().get('name%d' % i):
# do something
This question already has answers here:
Finding the index of an item in a list
(43 answers)
Closed 9 years ago.
I am trying to figure out how to determine if a tuple has an exact match in a list of tuples, and if so, return the index of the matching tuple. For instance if I have:
TupList = [('ABC D','235'),('EFG H','462')]
I would like to be able to take any tuple ('XXXX','YYYY') and see if it has an exact match in TupList and if so, what its index is. So for example, if the tuple ('XXXX','YYYY') = (u'EFG H',u'462') exactly, then the code will return 1.
I also don't want to allow tuples like ('EFG', '462') (basically any substring of either tuple element) to match.
Use list.index:
>>> TupList = [('ABC D','235'),('EFG H','462')]
>>> TupList.index((u'EFG H',u'462'))
1
I think you can do it by this
TupList = [('ABC D','235'),('EFG H','462')]
if ('ABC D','235') in TupList:
print TupList.index(i)
This question already has answers here:
How to retrieve a variable's name in python at runtime?
(9 answers)
Closed 9 years ago.
I've designed a code that calculates the percentage of 'CG' appears in a string; GC_content(DNA).
Now I can use this code so that it prints the the value of the string with the highest GC-content;
print (max((GC_content(DNA1)),(GC_content(DNA2)),(GC_content(DNA3)))).
Now how would I get to print the variable name of this max GC_content?
You can get the max of some tuples:
max_content, max_name = max(
(GC_content(DNA1), "DNA1"),
(GC_content(DNA2), "DNA2"),
(GC_content(DNA3), "DNA3")
)
print(max_name)
If you have many DNA variables you could place them in a list
DNA_list = [DNA1, DNA2, DNA3]
I would coerce them into a dictionary to associate the name with the raw data and result.
DNA_dict = dict([("DNA%i" % i, {'data': DNA, 'GC': GC_Content(DNA)}) for i, DNA in enumerate(DNA_list)])
Then list comprehension to get the data you want
name = max([(DNA_dict[key]['GC'], key) for key in DNA_dict])[1]
This has the benefit of allowing variable list length
You seem to want
max([DNA1, DNA2, DNA3], key=GC_content)
It's not what you asked for but it seems to be what you need.
This question already has answers here:
Removing set identifier when printing sets in Python
(5 answers)
Closed 9 years ago.
I have a list of sets (using Python).
Is there a way to print this without the "set([])" stuff around it and just output the actual values they are holding?
Right now I'm getting somthing like this for each item in the list
set(['blah', 'blahh' blahhh')]
And I want it to look more like this
blah,blahh,blahhh
Lots of ways, but the one that occurred to me first is:
s = set([0,1])
", ".join(str(e) for e in s)
Convert everything in the set to a string, and join them together with commas. Obviously your preference for display may vary, but you can happily pass this to print. Should work in python 2 and python 3.
For list of sets:
l = [{0,1}, {2,3}]
for s in l:
print(", ".join(str(e) for e in s))
I'm assuming you want a string representation of the elements in your set. In that case, this should work:
s = set([1,2,3])
print " ".join(str(x) for x in s)
However, this is dependent on the elements of s having a __str__ method, so keep that in mind when printing out elements in your set.
Assuming that your list of sets is called set_list, you can use the following code
for s in set_list:
print ', '.join(str(item) for item in s)
If set_list is equal to [{1,2,3}, {4,5,6}], then the output will be
1, 2, 3
4, 5, 6