How to convert a tuple to a string in Python? - python

After a MySQL select statement, I am left with the following:
set([('1#a.com',), ('2#b.net',), ('3#c.com',), ('4#d.com',), ('5#e.com',), ('6#f.net',), ('7#h.net',), ('8#g.com',)])
What I would like to have is a
emaillist = "\n".join(queryresult)
to in the end, have a string:
1#a.com
2#b.net
3#c.com
etc
What would be the proper way to convert this nested tuple into string?

As long as you're sure you have just one element per tuple:
'\n'.join(elem[0] for elem in queryresult)

A list comprehension along the lines of
[item[0] for item in queryresult]
should help. eg,
emaillist = "\n".join([item[0] for item in queryresult])
.. this makes strong assumptions about the type and structure of queryresult, however.
edit
A generator expression is even better at doing this:
emaillist = "\n".join(item[0] for item in queryresult)
thanks to #delnan for this update

Try this and see
>>> something=set([('1#a.com',), ('2#b.net',), ('3#c.com',), ('4#d.com',), ('5#e.com',), ('6#f.net',), ('7#h.net',), ('8#g.com',)])
>>> print '\n'.join(''.join(s) for s in something)
6#f.net
7#h.net
2#b.net
1#a.com
8#g.com
5#e.com
4#d.com
3#c.com
Note, join can only work on strings, but the items of the set are tuples. To make the join work, you have to iterate over the set to convert each item as string. Finally once done you can join them in the way your heart desires
On a side note. A circumbendibus way of doing it :-)
>>> print "\n".join(re.findall("\'(.*?)\'",pprint.pformat(something)))
1#a.com
2#b.net
3#c.com
4#d.com
5#e.com
6#f.net
7#h.net
8#g.com

new = '\n'.join(x[0] for x in old)

Related

Python how to get rid of a nested list

Good evening,
I have a python variable like so
myList = ["['Ben'", " 'Dillon'", " 'Rawr'", " 'Mega'", " 'Tote'", " 'Case']"]
I would like it to look like this instead
myList = ['Ben', 'Dillon', 'Rawr', 'Mega', 'Tote', 'Case']
If I do something like this
','.join(myList)
It gives me what I want but the type is a String
I also would like it to keep the type of List. I have tried using the Join method and split method. And I have been debugging use the type() method. It tells me that the type in the original scenario is a list.
I appreciate any and all help on this.
Join the inner list elements, then call ast.literal_eval() to parse it as a list of strings.
import ast
myList = ast.literal_eval(",".join(myList))
Also can be done by truncating Strings, therefore avoiding the import of ast.
myList[5] = (myList[5])[:-1]
for n in range(0, len(myList)):
myList[n] = (myList[n])[2:-1]

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)

Dicts in Python

I have a multidimensionnal dict, I need to return a specific value.
ConsomRatio={"DAP_Local":[],"MAP11_52":[]}
ConsomRatio["DAP_Local"].append({"Ammonia":"0.229", "Amine":"0.0007"})
ConsomRatio["MAP11_52"].append({"Ammonia":"0.138", "Fuel":"0.003"})
print(ConsomRatio["DAP_Local"])
The result of the print is:
[{'Ammonia': '0.229', 'Amine': '0.0007'}]
My question is : Is there a way to return the value of "Ammonia" only, in "DAP_Local" ?
Thank you!
You can get to it like this. You're appending your dict to a list, so you must select the correct index in the list where the dict is located. In this case the first element in the list or index 0.
ConsomRatio["DAP_Local"][0]["Ammonia"]
By the way, depending on what you are trying to achieve you might wanna take a look at the other answers for different implementations of multi-dimensional dicts.
The other answers are of course correct, but have you considered using a "dict of dicts"? i.e.:
ConsomRatio={"DAP_Local":{},"MAP11_52":{}}
ConsomRatio["DAP_Local"].update({"Ammonia":"0.229", "Amine":"0.0007"})
ConsomRatio["MAP11_52"].update({"Ammonia":"0.138", "Fuel":"0.003"})
print ConsomRatio["DAP_Local"]["Ammonia"]
0.229
since print(ConsomRatio["DAP_Local"]) returns an array of length 1, you need to select the index 0, then key off the 'Ammonia' value as above.
if print(ConsomRatio["DAP_Local"]) returned a dict, then no need to have the [0] and print(ConsomRatio["DAP_Local"]['Amomonia']) would have worked
Why are you putting lists in your dict, anyhow? You can just use dicts inside your main dict.
You can have multidimensional dicts also without the lists, e.g.:
ConsomRatio = {}
ConsomRation["DAP_Local"] = {"Ammonia":"0.229", "Amine":"0.0007"}
ConsomRatio["MAP11_52"] = {"Ammonia":"0.138", "Fuel":"0.003"}
print(ConsomRatio["DAP_Local"]["Ammonia"])
will give the desired result without the extra effort with the list.
You can get even shorter in Python:
ConsomRatio = {
"DAP_Local": {"Ammonia":"0.229", "Amine":"0.0007"},
"MAP11_52" : {"Ammonia":"0.138", "Fuel":"0.003"},
}
print(ConsomRatio["DAP_Local"]["Ammonia"])
To also answer your latest question (in your second comment):
to_produce = 'DAP_Local'
ingredience = 'Ammonia'
print('To produce {to_produce} we need {amount} of {ingredience}'.format(
to_produce=to_produce, ingredience=ingredience,
amount=ConsomRatio[to_produce].get(ingredience, '0.0')))
I hope, that helps!
It gets even better:
for product, ingred_list in ConsomRatio.items():
for iname, ivalue in ingred_list.items():
print('To produce {to_produce} we need {amount} of {ingredience}'
.format(to_produce=product, ingredience=iname,
amount=ivalue))

How to compare an element of a tuple (int) to determine if it exists in a list

I have the two following lists:
# List of tuples representing the index of resources and their unique properties
# Format of (ID,Name,Prefix)
resource_types=[('0','Group','0'),('1','User','1'),('2','Filter','2'),('3','Agent','3'),('4','Asset','4'),('5','Rule','5'),('6','KBase','6'),('7','Case','7'),('8','Note','8'),('9','Report','9'),('10','ArchivedReport',':'),('11','Scheduled Task',';'),('12','Profile','<'),('13','User Shared Accessible Group','='),('14','User Accessible Group','>'),('15','Database Table Schema','?'),('16','Unassigned Resources Group','#'),('17','File','A'),('18','Snapshot','B'),('19','Data Monitor','C'),('20','Viewer Configuration','D'),('21','Instrument','E'),('22','Dashboard','F'),('23','Destination','G'),('24','Active List','H'),('25','Virtual Root','I'),('26','Vulnerability','J'),('27','Search Group','K'),('28','Pattern','L'),('29','Zone','M'),('30','Asset Range','N'),('31','Asset Category','O'),('32','Partition','P'),('33','Active Channel','Q'),('34','Stage','R'),('35','Customer','S'),('36','Field','T'),('37','Field Set','U'),('38','Scanned Report','V'),('39','Location','W'),('40','Network','X'),('41','Focused Report','Y'),('42','Escalation Level','Z'),('43','Query','['),('44','Report Template ','\\'),('45','Session List',']'),('46','Trend','^'),('47','Package','_'),('48','RESERVED','`'),('49','PROJECT_TEMPLATE','a'),('50','Attachments','b'),('51','Query Viewer','c'),('52','Use Case','d'),('53','Integration Configuration','e'),('54','Integration Command f'),('55','Integration Target','g'),('56','Actor','h'),('57','Category Model','i'),('58','Permission','j')]
# This is a list of resource ID's that we do not want to reference directly, ever.
unwanted_resource_types=[0,1,3,10,11,12,13,14,15,16,18,20,21,23,25,27,28,32,35,38,41,47,48,49,50,57,58]
I'm attempting to compare the two in order to build a third list containing the 'Name' of each unique resource type that currently exists in unwanted_resource_types. e.g. The final result list should be:
result = ['Group','User','Agent','ArchivedReport','ScheduledTask','...','...']
I've tried the following that (I thought) should work:
result = []
for res in resource_types:
if res[0] in unwanted_resource_types:
result.append(res[1])
and when that failed to populate result I also tried:
result = []
for res in resource_types:
for type in unwanted_resource_types:
if res[0] == type:
result.append(res[1])
also to no avail. Is there something i'm missing? I believe this would be the right place to perform list comprehension, but that's still in my grey basket of understanding fully (The Python docs are a bit too succinct for me in this case).
I'm also open to completely rethinking this problem, but I do need to retain the list of tuples as it's used elsewhere in the script. Thank you for any assistance you may provide.
Your resource types are using strings, and your unwanted resources are using ints, so you'll need to do some conversion to make it work.
Try this:
result = []
for res in resource_types:
if int(res[0]) in unwanted_resource_types:
result.append(res[1])
or using a list comprehension:
result = [item[1] for item in resource_types if int(item[0]) in unwanted_resource_types]
The numbers in resource_types are numbers contained within strings, whereas the numbers in unwanted_resource_types are plain numbers, so your comparison is failing. This should work:
result = []
for res in resource_types:
if int( res[0] ) in unwanted_resource_types:
result.append(res[1])
The problem is that your triples contain strings and your unwanted resources contain numbers, change the data to
resource_types=[(0,'Group','0'), ...
or use int() to convert the strings to ints before comparison, and it should work. Your result can be computed with a list comprehension as in
result=[rt[1] for rt in resource_types if int(rt[0]) in unwanted_resource_types]
If you change ('0', ...) into (0, ... you can leave out the int() call.
Additionally, you may change the unwanted_resource_types variable into a set, like
unwanted_resource_types=set([0,1,3, ... ])
to improve speed (if speed is an issue, else it's unimportant).
The one-liner:
result = map(lambda x: dict(map(lambda a: (int(a[0]), a[1]), resource_types))[x], unwanted_resource_types)
without any explicit loop does the job.
Ok - you don't want to use this in production code - but it's fun. ;-)
Comment:
The inner dict(map(lambda a: (int(a[0]), a[1]), resource_types)) creates a dictionary from the input data:
{0: 'Group', 1: 'User', 2: 'Filter', 3: 'Agent', ...
The outer map chooses the names from the dictionary.

Python doesn't show anything

It's my first Python program and my first excercise is that I just need to swap places in a tuple:
stamboom = [("Frans","Eefje"), ("Klaar","Eefje"), ("Eefje","Mattho"),
("Eefje","Salammbo"), ("Gustave","Mattho"), ("Gustave","Salambo")]
Is the tuple, and I need to swap Frans with Eefje (those are just names) and then swap the second tuple.
I read the whole data structure tutorial off Python and I thought I could do this like this:
#!/path/to/python
stamboom = [("Frans","Eefje"), ("Klaar","Eefje"), ("Eefje","Mattho"),
("Eefje","Salammbo"), ("Gustave","Mattho"), ("Gustave","Salambo")]
def switchplace(x):
stamboom[x], stamboom[x + 1] = stamboom[x + 1], stamboom[x]
return stamboom
map(switchplace, range(0, len(stamboom)))
It doens't give syntax errors but it doesn't show anything.
To show something you have to print it.
Change the last line to:
print map(switchplace,range(0,len(stamboom)))
That was very complicated code for a simple task. Check out something called list comprehension.
Change the code to:
stamboom = [("Frans","Eefje"), ("Klaar","Eefje"), ("Eefje","Mattho"),
("Eefje","Salammbo"), ("Gustave","Mattho"), ("Gustave","Salambo")]
stamboom = [(item[1], item[0]) for item in stamboom]
print stamboom
Update
I saw your solution in the comment. I don't know if there are more premisses to the excersise that I'm not aware of. But I would probably do this instead:
def switchplace(x):
return x[1], x[0]
stamboom = [("Frans","Eefje"),("Klaar","Eefje"),("Eefje","Mattho"), ("Eefje","Salammbo"),("Gustave","Mattho"),("Gustave","Salammbo")]
print map(switchplace, stamboom)
The iterable argument to map don't have to be a numeric range. It could be the list itself. But maybe I missed something and you already got it :)
Tuples are immutable in Python:
http://docs.python.org/reference/datamodel.html

Categories