I need to declare certain values in List.
Values looks like this:
["compute","controller"], ["compute"] ,["controller"]
I know the List syntax in python is
example = []
I am not sure how I will include square brackets and double quotes in the List.
Could anyone please help.
I tried the following:
cls.node = ["\["compute"\]","\["controller"\]"]
cls.node = ["[\"compute\"]","[\"controller\"]"]
Both did not work.
I think you mean list not dictionary because that is the syntax of a list:
You can simply do it using the following format '"Hello"':
cls.node = ['["compute"]','["controller"]']
cls.node = ['["compute"]','["controller"]']
Demo:
s = ['["hello"]', '["world"]']
for i in s:
print i
[OUTPUT]
["hello"]
["world"]
Related
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]
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)
I have list with one item in it, then I try to dismantle, & rebuild it.
Not really sure if it is the 'right' way, but for now it will do.
I tried using replace \ substitute, other means of manipulating the list, but it didn't go too far, so this is what I came up with:
This is the list I get : alias_account = ['account-12345']
I then use this code to remove the [' in the front , and '] from the back.
NAME = ('%s' % alias_account).split(',')
for x in NAME:
key = x.split("-")[0]
value = x.split("-")[1]
alias_account = value[:-2]
alias_account1 = key[2:]
alias_account = ('%s-%s') % (alias_account1, alias_account)
This works beautifully when running print alias_account.
The problem starts when I have a list that have ['acc-ount-12345'] or ['account']
So my question is, how to include all of the possibilities?
Should I use try\except with other split options?
or is there more fancy split options ?
To access a single list element, you can index its position in square brackets:
alias_account[0]
To hide the quotes marking the result as a string, you can use print():
print(alias_account[0])
I have a string like this in python:
</info>;ct=0;if="sensor";obs;rt="urn:oma:lwm2m:oma:1",</time>;ct=0;if="sensor";rt="urn:oma:lwm2m:ext:3333",...
The objective is to have and print a list of the resources that contains "obs" like this: [/info, ...] the problem is that "obs" does not have to be in the same position.
At first I did a parse by (,) and with a loop for creates a list, then I want to filter by "obs" and finally parse again by ";" and remove the "<>" of the resources.
I started with this code but I am not sure how I should continue.
string = </info>;ct=0;if="sensor";obs;rt="urn:oma:lwm2m:oma:1",</time>;ct=0;if="sensor";rt="urn:oma:lwm2m:ext:3333",...
list = string.split(',')
for n in list:
if ";obs;" in list:
continue
print(n) # for check it
...
It doesn't work. Python can't find the "obs" in the object list. What is the problem? Can someone help me?
You need to do if ";obs;" in n in order to filter for that. Please have a look at this quick example:
string = '</info>;ct=0;if="sensor";obs;rt="urn:oma:lwm2m:oma:1",</time>;ct=0;if="sensor";rt="urn:oma:lwm2m:ext:3333",...'
list = string.split(',')
for n in list:
if ";obs;" in n:
print(n)
I hope that helps!
If I want to define a function called match_numbers, which would match the area code from one list to the phone number of another list, how should I fix my code? For example:
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
would give me
(666)313-2534
(332)123-3332
My code is:
def phone (nlist, nlist1):
results = {}
for x in nlist1:
results.setdefault(x[0:3], [])
results[x[0:3]].append(x)
for x in nlist:
if x in results:
print(results[x])
The problem with this code is, however:
It gives me the outputs in brackets, whereas I want it to print
the output line by line like shown above, and
it won't work with the parantheses in the 2nd list (for example
(666)543-2322 must be converted as 666-543-2322 for the list to
work.
Now, there are better/faster approaches to do what you are trying to do, but let us focus on fixing your code.
The first issue you have is how you are slicing your string. Remember that you start at index 0. So if you do:
x[0:3]
What you are actually getting is something like this from your string:
(12
Instead of your intended:
123
So, knowing that indexes start at 0, what you actually want to do is slice your string as such:
x[1:4]
Finally, your line here:
results[x[0:3]].append(x)
There are two problems here.
First, as mentioned above, you are still trying to slice the wrong parts of your string, so fix that.
Second, since you are trying to make a key value pair, what that above line is actually doing is making a key value pair where the value is a list. I don't think you want to do that. You want to do something like:
{'123': '(123)5556666'}
So, you don't want to use the append in this case. What you want to do is assign the string directly as the value for that key. You can do that as such:
results[x[1:4]] = x
Finally, another problem that was noticed, is in what you are doing here:
results.setdefault(x[1:4], [])
Based on the above explanation on how you want to store a string as your value in your dictionary instead of a list, so you don't need to be doing this. Therefore, you should simply be removing that line, it does not serve any purpose for what you are trying to do. You have already initialized your dictionary as results = {}
When you put it all together, your code will look like this:
def match_phone(nlist, nlist1):
results = {}
for x in nlist1:
results[x[1:4]] = x
for x in nlist:
if x in results:
print(results[x])
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
And will provide the following output:
(666)313-2534
(332)123-3332
If all the phone numbers will be in the format (ddd)ddd-dddd you can use
for number in (num for num in nlist1 if num[1:4] in nlist):
print(number)
You could use some better variable names than nlist and nlist1, in my view.
def match_phone(area_codes, numbers):
area_codes = set(area_codes)
for num in numbers:
if num in area_codes:
print num
You could do something like this:
phone_numbers = ['(443)241-1254', '(666)313-2534', '(332)123-3332']
area_codes = ['666', '332']
numbers = filter(lambda number: number[1:4] in area_codes, phone_numbers)
for number in numbers:
print(number)
Another similar way to do this without using a filter could be something like this:
for number in phone_numbers:
if number[1:4] in area_codes:
print(number)
Output in either case would be:
(666)313-2534
(332)123-3332
No one with regex solution! This may be an option too.
import re
def my_formatter(l1,l2):
mydic = {re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(2):re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(4) for i in l2}
for i in l1:
print "({0}){1}".format(str(i),str(mydic.get(i)))
my_formatter(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
It prints-
(666)313-2534
(332)123-3332