is it possible to get the first argument that contain a certain string in a named tuple such has:
import collections
data_line = collections.namedtuple('ex', 'a_1 b_1 a_2')
data = data_line(a_1=10, b_1=11, a_2=10)
getattr(data, 'a_2')
I would like to get the first argument that contain the string 'a', something like:
getattr(data, contains('a'))
any pythonic way to acheive this? thanks!
You can get it done by accessing the fields of the namedtuple and slicing the output to get your desired result:
Either:
[getattr(data, x) for x in data._fields if x.startswith('a')][0]
Or:
getattr(data, [x for x in data._fields if x.startswith('a')][0])
I hope this helps.
Maybe this is not what you want exactly but you can try something like this:
def contains(val):
if val.startswith('a'):
return True
else:
return False
for a in filter(contains, data._fields):
getattr(data, a)
and you may want to have a list of a's:
a_list = list(filter(contains, data._fields))
Related
def _parse_options(productcode_array):
if not self._check_productcode_has_options(productcode_array):
return None
possible_options = {"UV1", "UV2", "Satin", "Linen", "Unco", "Natural"}
option_index = productcode_array.index()
Example value of productcode_array:
["BC", "1.5x3.5", "100lb", "Linen", "Q100"]
My initial thought was to maybe try/except with a list comprehension but I feel there's probably a cleaner way I don't know about.
What I'm trying to achieve is getting the index position within my list productcode_array where any 1 of the possible_options exist. I know there will always only be 1 of the options present. The reason I need this is because the index position within the productcode is dependent on a number of factors.
What would be a clean and effective way to use index() with each of the values of my possible_options set?
>>> next(i for i, code in enumerate(productcode_array) if code in possible_options)
3
or
>>> productcode_array.index(possible_options.intersection(productcode_array).pop())
3
Example with try/except:
for x in possible_options:
try:
option_index = productcode_array.index(x)
except ValueError:
pass
This does work, but it feels dirty, so open to cleaner options.
You could use set.intersection and then assign to option_index (assuming there's only one common value, as stated in the comments):
For example:
possible_options = {"UV1", "UV2", "Satin", "Linen", "Unco", "Natural"}
productcode_array = ["BC", "1.5x3.5", "100lb", "Linen", "Q100"]
for v in possible_options.intersection(productcode_array):
option_index = productcode_array.index(v)
print(option_index)
Prints:
3
I want to make the input such that the user will type a separate number on each new line. I managed to put together this code
def str2arr(str):
arr = []
for line in str:
arr.append(str.replace('\n', ''))
return arr
import sys
a = sys.stdin.readlines()
print(a)
It is working nearly as I would like to, but the output looks like
['6543\n', '6543\n', '7654\n']
Is there a clever way to remove the \n?
And also, will I even get an usable integers using this method?
Thank you guys in advance.
You could use
a = ['6543\n', '6543\n', '7654\n']
integers = list(map(int, a))
print(integers)
# [6543, 6543, 7654]
Have a look at string.strip. That should provide the expected result.
You'll then have to call int() on each of the entries in the list.
Example:
>>> t = ['6543\n', '6543\n', '7654\n']
>>> [int(x.strip()) for x in t]
[6543, 6543, 7654]
What I want to achieve
value = 'a.b.c.d.e'
new_value = value.split('.')
new_value[-1] = F
''.join(new_value)
Now I would like to achieve this in one line. something like below
''.join(value[-1] = F in value.split('.'))
my above expression throws error because it is kind of wrong so is there a possible way to achieve this
Value should be "1.2.3.4.5" and join doesn't work for int. You should use new_value[-1]='10' instead.
''.join(value.split('.')[:-1]+['10'])
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
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"]