Using this code I was able to cycle through several instances of attributes and extract First and Last name if they matched the criteria. The results are a list of dict. How would i make all of these results which match the criteria, return as a full name each on it's own line as text?
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
print({players['firstName'], players['lastName']})
Results of Print Statement
{'Chandon', 'Sullivan'}
{'Urban', 'Brent'}
Are you looking for this:
print(players['firstName'], players['lastName'])
This would output:
Chandon Sullivan
Urban Brent
Your original trial just put the items to a set {}, and then printed the set, for no apparent reason.
Edit:
You can also for example join the firstName and lastName to be one string and then append the combos to a lists. Then you can do whatever you need with the list:
names = []
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
names.append(f"{players['firstName']} {players['lastName']}")
If you're using a version of Python lower than 3.6 and can't use f-strings you can do the last line for example like this:
names.append("{} {}").format(players['firstName'], players['lastName'])
Or if you prefer:
names.append(players['firstName'] + ' ' + players['lastName'])
Ok I figured out by appending the first and last name and creating a list for the found criteria. I then converted the list to a string to display it on the device.
full_list = []
my_snapshot = cfm.child('teamMap').get()
for players in my_snapshot:
if players['age'] != 27:
full_list.append((players['firstName'] + " " + players['lastName']))
send_message('\n'.join(str(i) for i in full_list))
I am generating all possible combinations for the given scrambled letters and storing it in a list. Then, I'm checking if words from that list are in my database. Although, the word is in the database, it is not returning so.
example for result list:
result = ['aargh', 'raagh', 'hraag']
Although there is a word called aargh in my database, its not returning it.
for r in result:
# print(r)
try:
actual = Dictionary.objects.get(word=r)
print(actual.word)
except:
actual = 'Not found'
print("Actual Word " + str(actual))
I have words stored in 'Dictionary' Table. What is wrong here?
you can check wheter the word exists or not:
for r in result:
actual = Dictionary.objects.filter(word__iexact=r).first()
if actual:
print(actual.word)
actual = actual.word
else:
actual = 'Not found'
print("Actual Word " + str(actual))
Try using icontains
Ex:
actual = Dictionary.objects.get(word__icontains=r)
Info on icontains
as the title says I am trying to get a exact match from any list of strings in a lists. I'm finding it hard to explain so ill show code now.
List = [['BOB','27','male'],['SUE','32','female'],['TOM','28','unsure']]
This would be an example of the lists layout, then i want to send information through from a web scrape to see if anything matches any of the item[0]+item[1]+item[2] in the list, the problem i am having is that the web scrape is using a for argument:-
HTML = requests.get(url).content
match = re.compile('Name"(.+?)".+?Age"(.+?)".+?Sex"(.+?)"').findall(HTML)
for name,age,sex in match:
Then my next part also using a for argument:-
for item in List:
if item[0] == name and item[1] == age and item[2] == sex:
pass
else:
print 'Name = '+name
print 'Age = '+age
print 'Sex = '+sex
But obviously if the result matches any of the single sets of lists it cannot match the other 2 so it will not pass, is there a way i can achieve it to check to see if it matches anything set of 3 results in the list name,age,and sex being item[0],item[1],item[2] exactly? I have also tried:
if all(item[0] == name and item[1] == age and item[2] == sex for item in List):
pass
This does not work, I'm assuming its because its not a direct match in all the lists of list and if i change all to any i get results coming back that skip if any of the strings match, ie age is 27,32 or 28. I know my regex is poor form and not the ideal way to parse HTML but its all I can use confidently at the moment sorry. Full code below for easier reading.
List = [['BOB','27','male'],['SUE','32','female'],['TOM','28','unsure']]
HTML = requests.get(url).content
match = re.compile('Name"(.+?)".+?Age"(.+?)".+?Sex"(.+?)"').findall(HTML)
for name,age,sex in match:
for item in List:
if item[0] == name and item[1] == age and item[2] == sex:
pass
else:
print 'Name = '+name
print 'Age = '+age
print 'Sex = '+sex
Any help would be greatly appreciated, I am still a beginner and have not used forum's much so I will apologise in advance if it's not grammatically correct or I have asked in the wrong way.
re.findall returns tuples, so you can simplify the comparison if the items in your list match the return type:
import re
# Changed sub-lists to tuples.
items = [('BOB','27','male'),('SUE','32','female'),('TOM','28','unsure')]
html = '''\
Name"BOB" Age"27" Sex"male"
Name"PAT" Age"19" Sex"unsure"
Name"SUE" Age"31" Sex"female"
Name"TOM" Age"28" Sex"unsure"
'''
for item in re.findall('Name"(.+?)".+?Age"(.+?)".+?Sex"(.+?)"', html):
if item in items:
name,age,sex = item
print 'Name =', name
print 'Age =', age
print 'Sex =', sex
print
Output:
Name = BOB
Age = 27
Sex = male
Name = TOM
Age = 28
Sex = unsure
You can also use item not in items if you want the ones that don't match.
First change the name of the list. List is not a reserved keyword,but it's not a good practice to use abstract names. My suggestion is to make the data a list. If I understood right your question, it's a matter of getting everything differently. So:
for sublist in my_list:
if (sublist[0] != weblist[0]) and (sublist[1] != weblist[1]) and (sublist[2] != weblist[2]):
print("List is different")
I have a large list of sub-strings that I want to search through and find if two particular sub-strings can be found in a row. The logic is intended to look for the first sequence, then if it is found, look at the second sub-string and return all the matches (based off the first 15 characters of the 16 character sequence). If the first sequence can not be found, it just looks for the second sequence only, and finally, if that can not be found, defaults to zero. The matches are then appended to a list, which is processed further. The current code used is as follows:
dataA = ['0100101010001000',
'1001010100010001',
'0010101000100010',
'0101010001000110',
'1010100010001110',
'0101000100011100',
'1010001000111010',
'0100010001110100',
'1000100011101000',
'0001000111010000']
A_vein_1 = [0,1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
joined_A_Search_1 = ''.join(map(str,A_vein_1))
print 'search 1', joined_A_Search_1
A_vein_2 = [1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
joined_A_Search_2 = ''.join(map(str,A_vein_2))
match_A = [] #empty list to append closest match to
#Match search algorithm
for i,text in enumerate(data):
if joined_A_Search_1 == text:
if joined_A_Search_2 == data[i+1][:-1]:
print 'logic stream 1'
match_A.append(data[i+1][-1])
if joined_A_Search_1 != text:
if joined_A_Search_2 == text[:-1]:
print 'logic stream 2'
#print 'match', text[:-1]
match_A.append(text[-1])
print ' A matches', match_A
try:
filter_A = max(set(match_A), key=match_A.count)
except:
filter_A = 0
print 'no match A'
filter_A = int(filter_A)
print '0utput', filter_A
The issue is that I get a return of both logic stream 1 and logic stream 2, when I actually want it to be a strict one or the other, in this case only logic stream 1. An example of the output looks like this:
search 1 0100101010001000
search 2 100101010001000
logic stream 1
logic stream 2
logic stream 1
logic stream 2
logic stream 2
(Note: The list has been shortened, and the data inputs have been substituted in directly, as well as the print outs for the purposes of this post and error tracking)
Input :
dataA = ['0100101010001000',
'1001010100010001',
'0010101000100010',
'0101010001000110',
'1010100010001110',
'0101000100011100',
'1010001000111010',
'0100010001110100',
'1000100011101000',
'0001000111010000']
A_vein_1 = [0,1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
A_vein_2 = [1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
code :
av1_str = "".join(map(str,A_vein_1))
av2_str = "".join(map(str,A_vein_2))
y=[av1_str,av2_str]
print [(y,dataA.index(x)) for x in dataA for y in dataB if y in x]
Output :
[('0100101010001000', 0), ('100101010001000', 0), ('100101010001000', 1)]
Your code confuses me. But I think I understand your issue:
#!/usr/env/env python
dataA = ['0100101010001000',
'1001010100010001',
'0010101000100010',
'0101010001000110',
'1010100010001110',
'0101000100011100',
'1010001000111010',
'0100010001110100',
'1000100011101000',
'0001000111010000']
A_vein_1 = [0,1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
A_vein_2 = [1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
av1_str = "".join(map(str,A_vein_1))
av2_str = "".join(map(str,A_vein_2))
for i, d in enumerate(dataA):
if av1_str in d:
print av1_str, 'found in line', i
elif av2_str in d:
print av2_str, 'found in line', i
This gives me :
jcg#jcg:~/code/python/stack_overflow$ python find_str.py
0100101010001000 found in line 0
100101010001000 found in line 0
100101010001000 found in line 1
After edit to elif:
jcg#jcg:~/code/python/stack_overflow$ python find_str.py
0100101010001000 found in line 0
100101010001000 found in line 1
I have a file at /location/all-list-info.txt underneath I have some items in below manner:
aaa:xxx:abc.com:1857:xxx1:rel5t2:y
ifa:yyy:xyz.com:1858:yyy1:rel5t2:y
I process these items with a below python code:
def pITEMName():
global itemList
itemList = str(raw_input('Enter pipe separated list of ITEMS : ')).upper().strip()
items = itemList.split("|")
count = len(items)
print 'Total Distint Item Count : ', count
pipelst = itemList.split('|')
filepath = '/location/all-item-info.txt '
f = open(filepath, 'r')
for lns in f:
split_pipe = lns.split(':', 1)
if split_pipe[0] in pipelst:
index = pipelst.index(split_pipe[0])
del pipelst[index]
for lns in pipelst:
print lns,' is wrong item Name'
f.close()
if podList:
After execution of above python code its gives a prompt as :
Enter pipe separated list of ITEMS:
And then I passes the items :
Enter pipe separated list of ITEMS: aaa|ifa-mc|ggg-mc
now after pressing enter above code process further like below :
Enter pipe separated list of ITEMS : aaa|ifa-mc|ggg-mc
Total Distint Item Count : 3
IFA-MC is wrong Item Name
GGG-MC is wrong Item Name
ITEMs Belonging to other Centers :
Item Count From Other Center = 0
ITEMs Belonging to Current Centers :
Active Items in US1 :
^IFA$
Test Active Items in US1 :
^AAA$
Ignored Item Count From Current center = 0
You Have Entered ItemList belonging to this center as: ^IFA$|^AAA$
Active Pod Count : 2
My question is if I suffix the '-mc' in items while giving the input its given me as wrong item whereas it presents in /location/all-item-info.txt file with not present the item in /location/all-item-info.txt . Please have a look at below output again :
IFA-MC is wrong Item Name
GGG-MC is wrong Item Name
In above example 'ifa' is present in /location/all-items-info.txt path whereas as ggg is not present.
Request you to help me here what can I do on above code so if I suffix the -mc which are present in /location/all-items-info.txt file it should not count as wrong item name. it should count only for those items which are not present in /location/all-items-info.txt file.
Please give you help.
Thanks,
Ritesh.
If you want to avoid checking for -mc as well, then you can modify this part of your script -
pipelst = itemList.split('|')
To -
pipelst = [i.split('-')[0] for i in itemList.split('|')]
It's a bit unclear exactly what you are asking, but basically to ignore any '-mc' from user input, you can explicitly preprocess the user input to strip it out:
pipelst = itemList.split('|')
pipelst = [item.rsplit('-mc',1)[0] for item in pipelst]
If instead you want to allow for the possibility of -mc-suffixed words in the file as well, simply add the stripped version to the list instead of replacing
pipelst = itemList.split('|')
for item in pipelist:
if item.endswith('-mc'):
pipelst.append(item.rsplit('-mc',1)[0])
Another issue may be based on the example lines you gave from /location/all-list-info.txt, it sounds like all the items are lowercase. However, pipelst is explicitly making the user input all uppercase. String equality and in mechanics is case-sensitive, so for instance
>>> print 'ifa-mc' in ['IFA-MC']
False
You probably want:
itemList = str(raw_input('Enter pipe separated list of ITEMS : ')).lower().strip()
and you could use .upper() only when printing or wherever it is needed
Finally, there are a few other things that could be tweaked with the code just to make things a bit faster and cleaner. The main one that comes to mind is it seems like pipelst should be a python set and not a list as checking inclusion and removal would then be much faster for large lists, and the code to remove an item from a set is much cleaner:
>>> desserts = set(['ice cream', 'cookies', 'cake'])
>>> if 'cake' in desserts:
... desserts.remove('cake')
>>> print desserts
set(['cookies', 'ice cream'])