Related
In every "for" loop, two items (user and likes) are taken from the "Data" list and are added to a separate list (scoreboard). I am trying to detect if "user" already exists in the scoreboard list. If it does exist, then I try to take the item that comes after "user" in the scoreboard list (which would be the previous "likes" item) and add the new "likes" item to it, after that I try to set the new "likes" item to the new value. but i couldn't make it work.
def likecount():
scoreboard = []
for t in range(0,len(Data),3):
user = Data[t]
likes = Data[t + 2]
if user not in scoreboard:
scoreboard.append(user), scoreboard.append(likes)
else:
scoreboard[(scoreboard.index(user) + 1)] + likes == scoreboard[(scoreboard.index(user) + 1)]
for i in range(0,len(scoreboard),2):
print (scoreboard[i],scoreboard[i+1], end= "\n")
#Data list:
['Rhett_andEmma77', 'Los Angeles is soooo hot', '0', 'Tato', 'Glitch', '1', 'Aurio', 'April fools tomorrow', '4', 'nap', 'The bully**', '3', 'NICKSION', 'Oops', '6', 'stupidfuck', 'hes a little guy', '5', 'database', 'Ty', '1', 'stupidfuck', 'possible object show (objects needed)', '3', 'NightSkyMusic', 'nicotine takes 10 seconds to reach your brain', '27', 'stupidfuck', '#BFBleafyfan99 be anii e', '4', 'Odminey', 'Aliveness', '26', 'stupidfuck', '#techness2011 the', '5', 'techness2011', 'Boomerang', '1', 'saltyipaint', 'April is r slur month', '5', 'HENRYFOLIO', 'flip and dunk', '4', 'SpenceAnimation', 'Got Any grapes 🍇', '2', 'RainyFox2', 'Draw me in your style****', '1', 'hecksacontagon', 'funky cat guy impresses you with his fish corpse', '11', 'HENRYFOLIO', 'flip and dunk #bruhkeko version', '4', 'nairb', 'Spoderman turns green', '5', 'SpenceAnimation', 'Jellybean', '1', 'SpenceAnimation', '#FussiArt', '3']
Dictiionary is precisely the thing you are looking for instead of keeping a list of items. So whenever a user is considered, you will check if he/she exists
If exists, then add the new likes to the old like count.
If it doesn't, create an entry with the like count.
That is the natural solution.
data = ['Rhett_andEmma77', 'Los Angeles is soooo hot', '0', 'Tato', 'Glitch', '1', 'Aurio', 'April fools tomorrow', '4', 'nap', 'The bully**', '3', 'NICKSION', 'Oops', '6', 'stupidfuck', 'hes a little guy', '5', 'database', 'Ty', '1', 'stupidfuck', 'possible object show (objects needed)', '3', 'NightSkyMusic', 'nicotine takes 10 seconds to reach your brain', '27', 'stupidfuck', '#BFBleafyfan99 be anii e', '4', 'Odminey', 'Aliveness', '26', 'stupidfuck', '#techness2011 the', '5', 'techness2011', 'Boomerang', '1', 'saltyipaint', 'April is r slur month', '5', 'HENRYFOLIO', 'flip and dunk', '4', 'SpenceAnimation', 'Got Any grapes 🍇', '2', 'RainyFox2', 'Draw me in your style****', '1', 'hecksacontagon', 'funky cat guy impresses you with his fish corpse', '11', 'HENRYFOLIO', 'flip and dunk #bruhkeko version', '4', 'nairb', 'Spoderman turns green', '5', 'SpenceAnimation', 'Jellybean', '1', 'SpenceAnimation', '#FussiArt', '3']
assert(len(data)%3 == 0)
scoreboard = {}
for i in range(0, len(data), 3):
if data[i] in scoreboard.keys():
scoreboard[data[i]]+= int(data[i+2])
else:
scoreboard[data[i]] = int(data[i+2])
print(scoreboard)
Output
{'Rhett_andEmma77': 0, 'Tato': 1, 'Aurio': 4, 'nap': 3, 'NICKSION': 6, 'stupidfuck': 17, 'database': 1, 'NightSkyMusic': 27, 'Odminey': 26, 'techness2011': 1, 'saltyipaint': 5, 'HENRYFOLIO': 8, 'SpenceAnimation': 6, 'RainyFox2': 1, 'hecksacontagon': 11, 'nairb': 5}
I have two list of strings (one is iOS ids, and the other App Name)
I'm trying to assign the app name to the ios id, respectively, when I iterate over a function that scrapes reviews. get_reviews() pulls the data from the app store using the App ID. I think I'm close but quite not there yet.
iosid = ['123456', '1324567', etc.]
name = ['Target', 'Facebook', etc.]
data = []
for j in iosid:
for i in name:
reviews = get_reviews(j)
result = [dict(item, app=i) for item in reviews]
data.append(result)
Example of output:
[{'review_id': '83323473', 'updated': '2022-02-13T19:05:11-07:00', 'title': 'I wish all apps were like this', 'author': 'john_doe', 'author_url': 'https://itunes.apple.com/us/reviews/id3435341', 'version': '2022.5', 'rating': '5', 'review': 'I love the app, super easy to use', 'vote_count': '0', 'page': 1, 'app': 'Target'},
{'review_id': '83323473', 'updated': '2022-02-13T19:05:11-07:00', 'title': 'Facebook changed', 'author': 'jim_doe', 'author_url': 'https://itunes.apple.com/us/reviews/id3234341', 'version': '2021.5', 'rating': '2', 'review': 'Super hard to use, don't recommend', 'vote_count': '0', 'page': 1, 'app': 'Facebook'}]
I think you could do like this
data = []
for id, name in zip(id_list, name_list):
reviews = get_reviews(id) # reviews is a list of dictionaries
# Add the field `app` with value `name` to each dictionary in `reviews`
result = [dict(item, app=name) for item in reviews]
data.append(result)
I'm not a coder by trade, rather an infrastructure engineer that's learning to code for my role. I have an output that I am getting and I am struggling to think how I can get this to work.
I've utilized some of my colleagues but the data is outputted in a weird format and I am unsure how to get the outcome I want. I have tried splitting the lines but it will not work perfectly.
The current code is simple. It just pulls the output command from the switch & I then have it split the lines:
output = net_connect.send_command("show switch")
switchlines = output.splitlines()
print(output)
print(switchlines[5])
It will then output the following in this case:
Switch/Stack Mac Address : 188b.45ea.a000 - Local Mac Address
Mac persistency wait time: Indefinite
H/W Current
Switch# Role Mac Address Priority Version State
------------------------------------------------------------
*1 Active 188b.45ea.a000 15 V01 Ready
2 Standby 00ca.e5fc.1780 14 V06 Ready
3 Member 00ca.e5fc.5e80 13 V06 Ready
4 Member 00ca.e588.f480 12 V06 Ready
5 Member 00ca.e588.ee80 11 V06 Ready
*1 Active 188b.45ea.a000 15 V01 Ready
That table comes out as a string & essentially, I need to find a way to split that into usable chunks (I.E a 2D Array) So I can use each field individually.
You already got the lines separated in a list (switchlines), so all you have left to do is iterate over that list and split each one on spaces. Because there are many spaces separating, we also want to strip those elements. So you could do something like:
res = []
for line in switchlines[5:]:
elements = [x.strip() for x in line.split()]
res.append(elements)
And this gives on your example text:
[['*1', 'Active', '188b.45ea.a000', '15', 'V01', 'Ready'],
['2', 'Standby', '00ca.e5fc.1780', '14', 'V06', 'Ready'],
['3', 'Member', '00ca.e5fc.5e80', '13', 'V06', 'Ready'],
['4', 'Member', '00ca.e588.f480', '12', 'V06', 'Ready'],
['5', 'Member', '00ca.e588.ee80', '11', 'V06', 'Ready']]
Another option that can later help you work on the data, is collect it into a dictionary instead of a list:
for line in switchlines[5:]:
switch, role, mac, prio, ver, state, *extras = [x.strip() for x in line.split()]
res.append({'switch': switch, 'role': role, 'mac': mac,
'prio': prio, 'ver': ver, 'state': state, 'extras': extras})
And this gives on your example text:
[{'switch': '*1', 'role': 'Active', 'mac': '188b.45ea.a000', 'prio': '15', 'ver': 'V01', 'state': 'Ready', 'extras': []},
{'switch': '2', 'role': 'Standby', 'mac': '00ca.e5fc.1780', 'prio': '14', 'ver': 'V06', 'state': 'Ready', 'extras': []},
{'switch': '3', 'role': 'Member', 'mac': '00ca.e5fc.5e80', 'prio': '13', 'ver': 'V06', 'state': 'Ready', 'extras': []},
{'switch': '4', 'role': 'Member', 'mac': '00ca.e588.f480', 'prio': '12', 'ver': 'V06', 'state': 'Ready', 'extras': []},
{'switch': '5', 'role': 'Member', 'mac': '00ca.e588.ee80', 'prio': '11', 'ver': 'V06', 'state': 'Ready', 'extras': []}]
I have created an archive(usersfile.txt) that contains the users information,
i want when i insert the username, if the username exist in the file return that the user exists and to refer me to the profile of the user(the profile is ok).Τhe problem is that i cannot find the user in the file.
The file is like:
{'user': 'mark', 'age': '20', 'city': ' london '},
{'user': 'jason', 'age': '28', 'city': ' london '},
{'user': 'john', 'age': '25', 'city': ' london '},
{'user': 'pit', 'age': '24', 'city': ' london '}
When i insert the first username ('mark) it works but when i insert the other usernames doesn't work.any suggestion?
is it better to do it with regex?(but i don't know how)
username = input('Enter Username:')
with open(usersfile.txt, 'r', encoding = 'utf-8') as f :
userfiles=[]
for userf in f:
userf = userf.split()
userfiles.append(userf)
for names in userfiles:
if username in names:
print('User {} exist :'.format(username))
UserProfile()
return True
else:
print('User {} doesn't exist :'.format(username))
return False
>>> user_props = {'user': 'mark', 'age': '20', 'city': ' london '},
{'user': 'jason', 'age': '28', 'city': ' london '},
{'user': 'john', 'age': '25', 'city': ' london '},
{'user': 'pit', 'age': '24', 'city': ' london '}
>>> # to find the person
>>> for person in user_props:
user_name = person.get('user')
if user_name and user_name == 'mark':
print(person)
{'user': 'mark', 'age': '20', 'city': ' london '}
>>> # just check if mark is a user
>>> any([it for it in user_props if it.get('user') is 'mark'])
True
You're going to want to do a binary search as this will be the fastest for searching a file of say usernames. For more information on a binary search look at this library for Python and this article. Another more purely vanilla Python way would be to load in the JSON and then loop through each user.
(Bad) Way
We load in the JSON with either an eval or the JSON library. Since you don't want to use other modules we'll use an eval. This is bad for many reasons mainly security and bugs that can break the program.
with open("users.txt") as f_in:
eval("data="+f_in.read())
Now that we have the "JSON" loaded in a variable, data, we can loop through the list of dictionaries and test for your user.
for u in data:
if u["user"] == user:
print("Found user: "+str (u))
break
Binary Search Method
One of the first things you'll want to do is sort the file, also making it either CSV or JSON will help rather than just plain text. I think CSV is best in this case so we'll create a users.csv file with the following content.
user,age,city
jason,28,london
john,25,london
mark,20,london
pit,24,london
And then our Python code will load the file and get the first column of user names. The most efficient way to do the binary search would be to keep the usernames sorted from the start. So when appending a name to the file or list of users you must insert it at the correct index such that the list will be sorted.
import csv
import pandas as pd
from bisect import bisect_left
with open("users.csv") as f_in:
df = pd.read_csv(f_in)
f_in.seek(0)
rows = [r for r in csv.reader(f_in)]
pos = bisect_left(df.name, user)
pos = pos if pos != len(df.name) and df.name[pos] == user else -1
if pos < 0:
print("The user was not found.")
else:
properties = "\n".join([x for x in rows[pos+1]])
print(f"User: {user} was found with properties:\n{properties}")
I have the following class setup:
class Card(object):
def __init__(self, name="", attack=0, defense=0, magic=0, shield=0, description=""):
self.name = name
self.attack = int(attack)
self.defense = int(defense)
self.magic = int(magic)
self.shield = int(shield)
self.description = description
I would like to make instances of Card using a list of dictionaries created from csv.dictreader.
Here is what the method for determining my cardList returns:
[
{'Magic': '200', 'Shield': '100', 'NameOfCard': 'Knight', 'Attack': '700', 'Defense': '400', 'Description': ''},
{'Magic': '500', 'Shield': '500', 'NameOfCard': 'Mage', 'Attack': '0', 'Defense': '0', 'Description': ''},
{'Magic': '100', 'Shield': '100', 'NameOfCard': 'Peasant', 'Attack': '100', 'Defense': '100', 'Description': ''},
{'Magic': '0', 'Shield': '0', 'NameOfCard': 'Lancer', 'Attack': '400', 'Defense': '100', 'Description': ''},
{'Magic': '100', 'Shield': '200', 'NameOfCard': 'Guardian', 'Attack': '100', 'Defense': '600', 'Description': ''},
...]
I was hoping to be able to use the 'NameOfCard' values to name the instances, and then map the values to the arguments taken by the __init__ method in the Card class.
My first thought was to do something like this:
Knight = Card(cardList[0]('NameOfCard')...)
But calling print Knight.name returns TypeError: 'dict' object is not callable.
How do I use my list of dicts to create instances of the Card class?
Use argument unpacking:
knight = Card(**dict_of_properties)
This will expand dict_of_properties into named arguments:
knight = Card(name='foo', stuff='bar')
Assuming dict_of_properties looks like:
dict_of_properties = {
'name': 'foo',
'stuff': 'bar'
}
If the argument names were the same as the dict keys then you could use:
Knight = Card(**cardList[0])
As it is you'll need to map the dict keys to the proper argument names first.