How can I call all items in a list item? - python

So in django, lets say you create a list through .append like so:
group = []
people = humans.objects.all()
for X in people:
X.update(name = Bob)
group.append(X.idnum)
If you wanted to get some of the items in the group list without it displaying like this " u'23' ",
you would have to call group[0] or any othe number to find the one youre looking for. My question is how can I get all of them at once without the u''. So if i have three peope in the group, I want their idnums to come out as 232528 instead of " u'23' u'25' u'28' " without me haveing to do group[0][1][2] since I want always know how many are in the list.

You want the str.join method. https://docs.python.org/2/library/stdtypes.html#str.join
"".join(group)
or if you want a number instead of a string
int("".join(group))

I would use a iteration and then add the string together:
list = [...]
result = ''
for item in list:
result += str(item)
The result would be '232528' if the items in the list are u'23' u'25' u'28'

Related

How to read and print a list in a specific order/format based on the content in the list for python?

New to python and for this example list
lst = ['<name>bob</name>', '<job>doctor</job>', '<gender>male</gender>', '<name>susan</name>', '<job>teacher</job>', '<gender>female</gender>', '<name>john</name>', '<gender>male</gender>']
There are 3 categories of name, job, and gender. I would want those 3 categories to be on the same line which would look like
<name>bob</name>, <job>doctor</job>, <gender>male</gender>
My actual list is really big with 10 categories I would want to be on the same line. I am also trying to figure out a way where if one of the categories is not in the list, it would print something like N/A to indicate that it is not in the list
for example I would want it to look like
<name>bob</name>, <job>doctor</job>, <gender>male</gender>
<name>susan</name>, <job>teacher</job>, <gender>female</gender>
<name>john</name>, N/A, <gender>male</gender>
What would be the best way to do this?
This is one way to do it. This would handle any length list, and guarantee grouping no matter how long the lists are as long as they are in the correct order.
Updated to convert to dict, so you can test for key existence.
lst = ['<name>bob</name>', '<job>doctor</job>', '<gender>male</gender>', '<name>susan</name>', '<job>teacher</job>', '<gender>female</gender>', '<name>john</name>', '<gender>male</gender>']
newlst = []
tmplist = {}
for item in lst:
value = item.split('>')[1].split('<')[0]
key = item.split('<')[1].split('>')[0]
if '<name>' in item:
if tmplist:
newlst.append(tmplist)
tmplist = {}
tmplist[key] = value
#handle the remaining items left over in the list
if tmplist:
newlst.append(tmplist)
print(newlst)
#test for existance
for each in newlst:
print(each.get('job', 'N/A'))

Change a list separator delimiter to another (python)

I need help using Python.
Supposing I have the list [22,23,45].
Is it possible to get an output like this: [22;23:45] ?
It's possible to change the delimiters if you display your list as a string. You can then use the join method. The following example will display your list with ; as a delimiter:
print(";".join(my_list))
This will only work if your list's items are string, by the way.
Even if you have more than one item
str(your_list[:1][0])+";" + ":".join(map(str,your_list[1:])) #'22;23:45'
Not sure why you want to wrap in the list but if you do just wrap around the above string in list()
my list which was [22,23,45] returned [;2;2;,; ;2;3;,; ;4;5;,] for both methods.
To bring more information, I have a variable:
ID= [elements['id'] for elements in country]
Using a print (ID), I get [22,23,45] so I suppose that the list is already to this form.
Problem is: I need another delimiters because [22,23,45] corresponds to ['EU, UK', 'EU, Italy', 'USA, California'].
The output I wish is [22,23,45] --> ['EU, UK'; 'EU, Italy'; 'USA, California']
I don't know if it's clearer but hope it could help
Try this I don't know exactly what do You want?
first solution:
list = [22,23,45]
str = ""
for i in list:
str += "{}{}".format(i, ";")
new_list=str[:-len(";")]
print(new_list)
and this is second solution
list = [22,23,45]
print(list)
list=str(list)
list=list.split(",")
list=";".join(list)
print(list)

Python: Removing characters from a string and then returning it

For example, given a list of strings prices = ["US$200", "CA$80", "GA$500"],
I am trying to only return ["US", "CA", "GA"].
Here is my code - what am I doing wrong?
def get_country_codes(prices):
prices = ""
list = prices.split()
list.remove("$")
"".join(list)
return list
Since each of the strings in the prices argument has the form '[country_code]$[number]', you can split each of them on '$' and take the first part.
Here's an example of how you can do this:
def get_country_codes(prices):
return [p.split('$')[0] for p in prices]
So get_country_codes(['US$200', 'CA$80', 'GA$500']) returns ['US', 'CA', 'GA'].
Also as a side note, I would recommend against naming a variable list as this will override the built-in value of list, which is the type list itself.
There are multiple problems with your code, and you have to fix all of them to make it work:
def get_country_codes(prices):
prices = ""
Whatever value your caller passed in, you're throwing that away and replacing it with "". You don't want to do that, so just get rid of that last line.
list = prices.split()
You really shouldn't be calling this list list. Also, split with no argument splits on spaces, so what you get may not be what you want:
>>> "US$200, CA$80, GA$500".split()
['US$200,', 'CA$80,', 'GA$500']
I suppose you can get away with having those stray commas, since you're just going to throw them away. But it's better to split with your actual separators, the ', '. So, let's change that line:
prices = prices.split(", ")
list.remove("$")
This removes every value in the list that's equal to the string "$". There are no such values, so it does nothing.
More generally, you don't want to throw away any of the strings in the list. Instead, you want to replace the strings, with strings that are truncated at the $. So, you need a loop:
countries = []
for price in prices:
country, dollar, price = price.partition('$')
countries.append(country)
If you're familiar with list comprehensions, you can rewrite this as a one-liner:
countries = [price.partition('$')[0] for price in prices]
"".join(list)
This just creates a new string and then throws it away. You have to assign it to something if you want to use it, like this:
result = "".join(countries)
But… do you really want to join anything here? It sounds like you want the result to be a list of strings, ['US', 'CA', 'GA'], not one big string 'USCAGA', right? So, just get rid of this line.
return list
Just change the variable name to countries and you're done.
Since your data is structured where the first two characters are the county code you can use simple string slicing.
def get_country_codes(prices):
return [p[:2] for p in prices]
You call the function sending the prices parameter but your first line initialize to an empty string:
prices = ''
I would also suggest using the '$' character as the split character, like:
list = prices.split('$')
try something like this:
def get_country_codes(prices):
list = prices.split('$')
return list[0]

How to dynamically append to array in dict?

This has taken me over a day of trial and error. I am trying to keep a dictionary of queries and their respective matches in a search. My problem is that there can be one or more matches. My current solution is:
match5[query_site] will already have the first match but if it finds another match it will append it using the code below.
temp5=[] #temporary variable to create array
if isinstance(match5[query_site],list): #check if already a list
temp5.extend(match5[query_site])
temp5.append(match_site)
else:
temp5.append(match5[query_site])
match5[query_site]=temp5 #add new location
That if statement is literally to prevent extend converting my str element into an array of letters. If I try to initialize the first match as a single element array I get None if I try to directly append. I feel like there should be a more pythonic method to achieve this without a temporary variable and conditional statement.
Update: Here is an example of my output when it works
5'flank: ['8_73793824', '6_133347883', '4_167491131', '18_535703', '14_48370386']
3'flank: X_11731384
There's 5 matches for my "5'flank" and only 1 match for my "3'flank".
So what about this:
if query_site not in match5: # here for the first time
match5[query_site] = [match_site]
elif isinstance(match5[query_site], str): # was already here, a single occurrence
match5[query_site] = [match5[query_site], match_site] # make it a list of strings
else: # already a list, so just append
match5[query_site].append(match_site)
I like using setdefault() for cases like this.
temp5 = match5.setdefault(query_site, [])
temp5.append(match_site)
It's sort of like get() in that it returns an existing value if the key exists but you can provide a default value. The difference is that if the key doesn't exist already setdefault inserts the default value into the dict.
This is all you need to do
if query_site not in match5:
match5[query_site] = []
temp5 = match5[query_site]
temp5.append(match_site)
You could also do
temp5 = match5.setdefault(query_site, [])
temp5.append(match_site)
Assuming match5 is a dictionary, what about this:
if query_site not in match5: # first match ever
match5[query_site] = [match_site]
else: # entry already there, just append
match5[query_site].append(temp5)
Make the entries of the dictionary to be always a list, and just append to it.

Variable that returns complete string inside list

I have this code:
topic = "test4"
topics = sns.get_all_topics()
topicsList = topics['ListTopicsResponse']['ListTopicsResult']['Topics']
topicsListNames = [t['TopicArn'] for t in topicsList]
That returns a list:
[u'arn:aws:sns:us-east-1:10:test4', u'arn:aws:sns:us-east-1:11:test7']
What Im trying now is create a variable that returns the complete string relative to the topic variable.
I have the variable topic = "test4", and I want to have a variable topicResult that returns u'arn:aws:sns:us-east-1:10:test4.
The string relative to topic its not always in list 1st position.
Do you know how to do this?
topicResult = " ".join([t['TopicArn'] for t in topicsList if t['TopicArn'].endswith(topic)])
This will check the strings in the list to see if the topic variable is the end of one of the strings. " ".join() gives you a string, but if you want to keep a list of the strings that end with topic, you can get rid of it. If topic won't always be at the end of the string, you can just check if topicis inside the string.
topicResult = " ".join([t['TopicArn'] for t in topicsList if topic in t['TopicArn']])
You could use intention lists, with a check statement in, but I think built-in filter will be faster:
topicsListNames = filter(lambda item: item['TopicArn'].endswith(topic), topicsList)
Basically, this line take the topicsList, then takes only the items item for which item['TopicArn'].endswith(topic) is True, ie. the items whose 'TopicArn' element ends with the reference of the topic variable. Finally, all these "good" items are returned, and topicsListNames references them.

Categories