This my schema for the tuple:
(name, age, weight)
UserList = (('steve', 17, 178), ('Mike', 19, 178),('Pull', 24, 200),('Adam', 15, 154))
I want to check is the age is less than 18 I would like to replace the the tuple for that user with ( , , )
so the final result will looks like
(('', , ), ('Mike', 19, 178),('Pull', 24, 200),('', , ))
I tried
UserList = list(UserList)
for i,e in enumerate(UserList):
if e[1] < 18:
temp=list(UserList[i])
for f, tmp in enumerate(temp):
del temp[:]
But it didn't work, any thoughts or suggestions will be highly appreciated.
Thanks!
In [13]: UserList = tuple((n, a, w) if a >= 18 else ('', None, None) for (n, a, w) in UserList)
In [14]: UserList
Out[14]: (('', None, None), ('Mike', 19, 178), ('Pull', 24, 200), ('', None, None))
Related
How to extract column names along with their conditions applied from a SQL query string using Python, so that I can map the result to other table and get the required data?
query = "SELECT COUNT(*) as cnt FROM dbo.main_table WHERE (VKRKA10001920015 = 1 AND age IN (15, 16, 17, 18, 19) AND income IN (101, 102, 301, 302, 305))"
Required_Output = {
'VKRKA10001920015': 1,
'age' : (15, 16, 17, 18, 19),
'income' : (101, 102, 301, 302, 305),
}
As of now I am able to extract only column names using sql-metadata python package. But I need the conditions as well to perform other operations
from sql_metadata.compat import get_query_columns
print(get_query_columns(query))
['VKRKA10001920015', 'age', 'householdincome']
To identify the tokens ("IN", "=", "LIKE") I have used the get_tokens() which recursively get the tokens added to the extracted_key() dictionary. Here in the extracted_keys dict the key address stored instead of the actual key Since the functions is going recursively. So I have used create_dict() another function to create a proper dictionary out of extracted_keys dictionary. For now we are able to extract columns along with their conditions from the SQL WHERE conditon for following operators i.e., "IN" operator, "=" operator, "Like" operator.
To install sqlparse module
pip install sqlparse
import sqlparse
def get_tokens(where):
identifier = None
extracted_keys = {}
for i in where.tokens:
try:
name = i.get_real_name()
if name and isinstance(i, sqlparse.sql.Identifier):
name = i.get_real_name()
identifier = i
extracted_keys[identifier] = i.value
elif identifier and isinstance(i, sqlparse.sql.Parenthesis):
extracted_keys[identifier] = i.value
elif i and "in" not in i.value.lower() and "or" not in i.value.lower() and isinstance(i, sqlparse.sql.Comparison):
if "=" in i.value:
equal_index = i.value.index("=")
if i.value[equal_index -1] not in ["!", ">", "<"]:
key,value = i.value.split("=")[0], i.value.split("=")[1]
extracted_keys[key] = value
if "!=" in i.value:
key,value = i.value.split("!=")[0], i.value.split("!=")[1]
extracted_keys[key] = value
elif "like" in i.value.lower():
key,value = i.value.lower().split("like")[0].upper(), i.value.lower().split("like")[1]
extracted_keys[key] = value
else:
extracted_keys.update(get_tokens(i))
except Exception as error:
pass
return extracted_keys
def create_dict(extracted_keys):
cols = {}
for key, value in extracted_keys.items():
try:
if key.get_real_name():
cols[key.get_real_name()] = value
except Exception as e:
cols[key] = value
return cols
For example:
query = "SELECT COUNT(*) as cnt FROM dbo.main_table WHERE (VKRKA10001920015 = 1 AND age IN (15, 16, 17, 18, 19) AND income IN (101, 102, 301, 302, 305))"
parsed = sqlparse.parse(query)
where = parsed[0][-1]
extracted_keys = get_tokens(where)
extracted_keys = create_dict(extracted_keys)
Output
{
'VKRKA10001920015': 1,
'age' : (15, 16, 17, 18, 19),
'income' : (101, 102, 301, 302, 305),
}
I have this bad boy:
def by_complexity(db : {str: {(int,int) : float}}) -> [(str,int)]:
complex = []
for state, taxes in db.items():
complex.append((state, len(taxes.values())))
return (sorted(complex, key = lambda zps : (-zps[1],zps[0])))
db1 = {'CT': {( 0, 12_499): .02,
( 12_500, 49_999): .04,
( 50_000, None): .06},
'IN': {(0, None): .04},
'LA': {( 0, 9_999): .03,
( 10_000, 12_499): .05,
( 12_500, 49_999): .055,
( 50_000, 299_999): .06,
(300_000, None): .078},
'MA': {(0, None): .055}}
print(by_complexity(db1))
Now when I run it, it only prints out [('CT', 3)]
instead of [('LA', 5), ('CT', 3), ('IN', 1), ('MA', 1)] so now I'm wondering why? because I can't find a bug in it... it just doesn't work
It's coming from your indent level with your return.
You are returning while still in your for loop.
Try this :
def by_complexity(db: {str: {(int, int): float}}) -> [(str, int)]:
complex = []
for state, taxes in db.items():
complex.append((state, len(taxes.values())))
return (sorted(complex, key=lambda zps: (-zps[1], zps[0])))
Heys, I recently couldnt figure out how to blit lists onto my pygame screen using certain x and y values, allowing the text to blit say x += 20, moving every other string in my list over 20 units everytime it blits. I recently did some .format stuff with printing just in the console, is there a feature like this for screen.blit so I can use the same formatting in a pygame window? Included my code underneath. Thanks in advance :D
import pygame
NAMES = ['Deanerys T.', 'Jon S.', 'Gregor C.', 'Khal D.', 'Cersei L.', 'Jamie L.',
'Tyrion L.', 'Sansa S.', 'Ayra S.', 'Ned S.']
DATE_OF_BIRTH = ['6/10/1996', '6/12/1984', '3/12/1980', '8/4/1986', '7/2/1970',
'7/2/1975', '12/24/1980', '11/30/1993', '5/18/1999', '6/27/1984']
AGE = [22, 34, 38, 32, 48, 43, 38, 25, 19, 34]
MARITAL_STATUS = ['Not Married', 'Not Married', 'Not Married', 'Not Married',
'Married', 'Not Married', 'Married', 'Married', 'Not Married', 'Married']
NUM_OF_CHILDREN = [3, 0, 0, 4, 2, 0, 1, 1, 0, 5]
for i in range(10):
print("{:>12} was born {:>10}, is age {:>2}. They have {:>1} children, and are {:>4}".format(NAMES[i], DATE_OF_BIRTH[i], AGE[i], NUM_OF_CHILDREN[i], MARITAL_STATUS[i]))
print("\n")
for i in range(10):
print("NAME: {:>12} DATE OF BIRTH: {}".format(NAMES[i], DATE_OF_BIRTH[i], ))
print("\n")
for i in range(10):
print("NAME: {:>12} AGE: {}".format(NAMES[i], AGE[i], ))
print("\n")
for i in range(10):
print("NAME: {:>12} MARRIAGE STATUS: {}".format(NAMES[i], MARITAL_STATUS[i], ))
print("\n")
for i in range(10):
print("NAME: {:>12} NUMBER OF CHILDREN: {}".format(NAMES[i], NUM_OF_CHILDREN[i], ))
print("\n")
The format is an operator on the string, so it's no problem to use it with pygame.
For Example:
hp = 56
player_hp_text = "Hit Points: {:>3}".format( hp )
player_hp_bitmap = myfont.render( player_hp_text, 16, (255, 255,0) )
screen.blit( player_hp_bitmap, ( 10, 10 ) )
How can I sort these tuples by time interval, say every hour?
[('172.18.74.146', datetime.time(11, 28, 58)), ('10.227.211.244',
datetime.time(11, 54, 19)), ('10.227.215.68', datetime.time(11, 54, 34)),
('10.227.209.139', datetime.time(12, 14, 47)), ('10.227.147.98',
datetime.time(14, 47, 25))]
The result should be:
[["172.18.74.146, 10.227.211.244, 10.227.215.68", "11-12"], etc...]
I tried to use group by, but doesnt get what I want:
for dd in data[1:]:
ips = dd[1].split(",")
dates = dd[2].split(",")
i = 0
while(i < len(dates)):
ips[i] = ips[i].strip()
hour, mins, second = dates[i].strip().split(":")
dates[i] = datetime.time(int(hour), int(mins), int(second))
i+=1
order = [(k, ', '.join(str(s[0]) for s in v)) for k, v in groupby(sorted(zip(ips, dates), key=operator.itemgetter(1)), lambda x: x[1].hour)]
In [17]: a = [('172.18.74.146', datetime.time(11, 28, 58)), ('10.227.211.244',
datetime.time(11, 54, 19)), ('10.227.215.68', datetime.time(11, 54, 34)),
('10.227.209.139', datetime.time(12, 14, 47)), ('10.227.147.98',
datetime.time(14, 47, 25))]
In [18]: [(k, ', '.join(str(s[0]) for s in v)) for k, v in groupby(a, lambda x: x[1].hour)]
Out[18]:
[(11, '172.18.74.146, 10.227.211.244, 10.227.215.68'),
(12, '10.227.209.139'),
(14, '10.227.147.98')]
This should work for you:
from __future__ import print_function
import datetime
import itertools
def iter_len(iterable):
return sum(1 for __ in iterable)
def by_hour(item): # Hour key
timestamp = item[1]
return '{}-{}'.format(timestamp.hour, (timestamp.hour+1) % 24)
def by_half_hour(item): # Half-hour key
timestamp = item[1]
half_hour = timestamp.hour + (0.5 * (timestamp.minute // 30))
return '{:.1f}-{:.1f}'.format(half_hour, (half_hour+0.5) % 24)
def get_results(data, key): # Name this more appropriately
data = sorted(data, key=key)
for key, grouper in itertools.groupby(data, key):
yield (key, iter_len(grouper))
data = [
('172.18.74.146', datetime.time(11, 28, 58)),
('10.227.211.244', datetime.time(11, 54, 19)),
('10.227.215.68', datetime.time(11, 54, 34)),
('10.227.209.139', datetime.time(12, 14, 47)),
('10.227.147.98', datetime.time(14, 47, 25)),
]
print('By Hour')
print(list(get_results(data, by_hour)))
print()
print("By Half Hour")
print(list(get_results(data, by_half_hour)))
Output:
$ ./SO_32081251.py
By Hour
[('11-12', 3), ('12-13', 1), ('14-15', 1)]
By Half Hour
[('11.0-11.5', 1), ('11.5-12.0', 2), ('12.0-12.5', 1), ('14.5-15.0', 1)]
This is almost what you want. Use the hour to group by:
for k,g in itertools.groupby(order, lambda x: x[1].hour):
print k,list(g)
Results in:
11 [('172.18.74.146', datetime.time(11, 28, 58)), ('10.227.211.244', datetime.time(11, 54, 19)), ('10.227.215.68', datetime.time(11, 54, 34))]
12 [('10.227.209.139', datetime.time(12, 14, 47))]
14 [('10.227.147.98', datetime.time(14, 47, 25))]
I have the following code
class Tupla:
def __init__(self, xid, prob):
self.xid = xid
self.prob = prob
and I append to a list some objects of this class
print myList1
>> [('X10', 11, ''), ('X9', 11, ''), ('X11', 11, ''), ('X2', 11, '')]
I try to order it
myList1 = sorted(myList1, key=lambda Tupla: Tupla.xid, reverse=True)
print myList1
>> [('X9', 11, ''), ('X2', 11, ''), ('X11', 11, ''), ('X10', 11, '')]
I am looking for human sorting. I need order the list like this:
[('X2', 11, ''), ('X9', 11, ''), ('X10', 11, ''), ('X11', 11, '')]
How can I do that?
def Tupla(xid, prob):
class _Tupla:
def __init__(self):
pass
def get_id(self):
return xid
def get_prob(self):
return prob
return _Tupla()
myList = map(lambda arg: Tupla(*arg), (('X10', 11), ('X9', 11), ('X11', 11), ('X2', 11)))
myList.sort(key = lambda obj: int(obj.get_id()[1:]))
print [(x.get_id(), x.get_prob()) for x in myList]
Output:
[('X2', 11), ('X9', 11), ('X10', 11), ('X11', 11)]