Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a list:
Online = [['Robot1', '23.9', 'None', '0'], ['Robot2', '25.9', 'None', '0']]
and i want to replace the sublist if i received different values:
NewSublist1 = ['Robot1', '30.9', 'Sending', '440']
NewSublist2 = ['Robot2', '50']
And i want:
Online = [['Robot1', '30.9', 'Sending', '440'], ['Robot2', '50']]
The number of the sublist elements could change. The only thing that is the same is the Robot id. So i want to make a search, see if the Robot id is on the Online list and replace the sublist with the new one.
You can create a dictionary mapping the robot IDs in your new sublists to the actual new sublists, then look up the existing robot IDs in that dict and replace accordingly.
>>> Online = [['Robot1', '23.9', 'None', '0'], ['Robot3', 'has no replacement'], ['Robot2', '25.9', 'None', '0']]
>>> NewSublists = [['Robot1', '30.9', 'Sending', '440'], ['Robot2', '50'], ['Robot4', 'new entry']]
>>> newsub_dict = {sub[0]: sub for sub in NewSublists}
>>> [newsub_dict.get(sub[0], sub) for sub in Online]
[['Robot1', '30.9', 'Sending', '440'],
['Robot3', 'has no replacement'],
['Robot2', '50']]
This will loop over each element in the list once, giving it a complexity of O(n), n being the number of elements in the Online list. If, instead, you make Online also a dictionary mapping robot IDs to sublists, you could get this down to O(k), k being the number of new sublists.
If you also want to add elements from NewSublists to Online if those are not yet present, you should definitely convert Online to a dict as well; then you can simply update the dict and get the values. Ir order matters, make sure to use a collections.OrderedDict or Python 3.7.
>>> online_dict = {sub[0]: sub for sub in Online}
>>> online_dict.update(newsub_dict)
>>> list(online_dict.values())
[['Robot1', '30.9', 'Sending', '440'],
['Robot3', 'has no replacement'],
['Robot2', '50'],
['Robot4', 'new entry']]
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
How do I print the value of animals from the list?
[{'Url': 'https://www.somewebsite.html',
'Fruits': [],
'Animals': ['Fox'],
'Cars': ['Toyota']},
Thats is an dictionary inside list, so
l = [{'Url': 'https://www.somewebsite.html',
'Fruits': [],
'Animals': ['Fox'],
'Cars': ['Toyota']},
print(l[0]) # return dictionary
print(l[0]['Animals']) # return the list '['Fox']', that can be accessed by index 0.
I don't see the point of a list in there so I think what you are looking for is a dictionary that looks like this:
d = {
'key': 'value',
...
}
This is the easiest way to have paired items and to have a keyword that will give you more information about something. For example it could be used as information about products in a store where you can get the price and category for example.
To access these values you simply use this line of code: d['key'] or d.get('key')
So for this example you want to organize your items inside a dictionary like this:
items = {
'Fruits': [],
'Animals': ['Fox'],
'Cars': ['Toyota']
}
print(items['Animals']) # This gives you the list that in this example looks like this: ['Fox']
animals = items['Animals'] # This stores the list from above in a variable
print(items['Animals'][0]) # Out: 'Fox'
print(items.get('Animals')[0]) # Out: 'Fox'
print(animals[0]) # Out: 'Fox'
Hi I'm fairly new to Python and needed help with extracting strings from a list. I am using Python on Visual Studios.
I have hundreds of similar strings and I need to extract specific information so I can add it to a table in columns - the aim is to automate this task using python. I would like to extract the data between the headers 'Names', 'Ages' and 'Jobs'. The issue I am facing is that the number of entries of names, ages and jobs varies a lot within all the lists and so I would like to write unique code which could apply to all the lists.
list_x = ['Names','Ashley','Lee','Poonam','Ages', '25', '35', '42' 'Jobs', 'Doctor', 'Teacher', 'Nurse']
I am struggling to extract
['Ashley', 'Lee', 'Poonam']
I have tried the following:
for x in list_x:
if x == 'Names':
for y in list_x:
if y == 'Ages':
print(list_x[x:y])
This however comes up with the following error:
"Exception has occurred: typeError X
slice indices must be integers or None or have an index method"
Is there a way of doing this without specifying exact indices?
As the comment suggested editing the data is the easiest way to go, but if you have to...
newList = oldList[oldList.index('Names') + 1:oldList.index("Ages")]
It just finds the indices of "Names" and "Ages" in the list, and extracts the bit between.
Lots can (and will) go wrong with this method though - if there's a name which is "Names", or if they are misspelt, etc.
For completeness sake, it might be not a bad idea to use an approach similar to the below.
First, build a list of indices of each of the desired headers:
list_x = ['Names', 'Ashley', 'Lee', 'Poonam', 'Ages', '25', '35', '42', 'Jobs', 'Doctor', 'Teacher', 'Nurse']
headers = ('Names', 'Ages', 'Jobs')
header_indices = [list_x.index(header) for header in headers]
print('indices:', header_indices) # [0, 4, 8]
Then, create a list of values for each header, which we can infer from the positions where each header shows up in the list:
values = {}
for i in range(len(header_indices)):
header = headers[i]
start = header_indices[i] + 1
try:
values[header] = list_x[start:header_indices[i + 1]]
except IndexError:
values[header] = list_x[start:]
And finally, we can display it for debugging purposes:
print('values:', values)
# {'Names': ['Ashley', 'Lee', 'Poonam'], 'Ages': ['25', '35', '42'], 'Jobs': ['Doctor', 'Teacher', 'Nurse']}
assert values['Names'] == ['Ashley', 'Lee', 'Poonam']
For better time complexity O(N), we can alternatively use an approach like below so that we only have one for loop over the list to build a dict object with the values:
from collections import defaultdict
values = defaultdict(list)
header_idx = -1
for x in list_x:
if x in headers:
header_idx += 1
else:
values[headers[header_idx]].append(x)
print('values:', values)
# defaultdict(<class 'list'>, {'Names': ['Ashley', 'Lee', 'Poonam'], 'Ages': ['25', '35', '42'], 'Jobs': ['Doctor', 'Teacher', 'Nurse']})
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
This is a similar problem posted here lots of time but I am unable to get my head around it.
import json
str2 ="""[{'cta': [], 'ctr': 2880509, 'client_id': '229132', 'exchange': 'NSE_EQ', 'token': '3063', 'product': 'CO', 'order_type': 'M', 'duration': 'DAY', 'price': '0', 'trigger_price': '149.10', 'quantity': 1, 'disclosed_quantity': 0, 'side': 'S', 'avg_price': '148.10', 'traded_quantity': 1, 'pending_quantity': 0, 'message': '', 'exchange_order_id': '1300000006005800', 'syom_order_id': 'NA', 'order_number': '191101000336718', 'timestamp': '01/11/2019,12:19:45', 'exchange_timestamp': '01-Nov-2019 12:19:45', 'status': 'complete', 'time_in_micro': '1572590985928000', 'is_amo': False, 'order_complexity': 'CO', 'request_id': '1', 'valid_date': '--', 'tag': 'JWEB|TB1', 'comments': 'PLACE ORDER :: 229132|NSE_EQ|3063|EQ|I|0|1|S|CO|WEB|IP-172-31-4-125|1572590985897', 'fill_id': '', 'original_message': '', '_amo': False}]"""
str2 = (json.dumps(str2))
print(str2)
print(str2['client_id'])
Why this doesn't work? It says -
print(str2['client_id'])
TypeError: string indices must be integers
Note that str2 is output from someplace and my goal is to fetch the client_id or any other variable.
So what I am seeking is what is the possible way to parse it?
There are mutliple problems here. You don't seem to be thinking this through.
You start with a string. Calling json.dumps on a string just gives you another string. But you couldn't have called json.loads on the original string either, because it is not JSON; it appears to be a string representation of a Python object.
But then, even if you had correctly parsed it, it still wouldn't work, because it represents a list of dictionaries, not a single dict.
It seems unlikely that this is actually the output from your external system. If you want further help, you will need to explain exactly how you got that string.
This question already has answers here:
How to print a list in Python "nicely"
(11 answers)
Closed 5 years ago.
I've used a draft code and adapted it to suit my code but I don't know how to split the data. The question might seem a vague so I'll try to be help by saying what I want.
My code:
import csv
with open("scores.csv") as csv_data:
reader=csv.reader(csv_data,delimiter=",")
number_sorted=sorted(reader,key=lambda x:int(x[0]),reverse=True)
print(number_sorted)
I get the output:
[['25356767', 'tom'], ['443388', 'jin'], ['6744', 'trev'], ['4666', 'ryan'],
['2445', 'jones'], ['536', 'sue'], ['34', 'bob'], ['8', 'hera'], ['1',
'bill'], ['0', 'v']]
but I want the print to look like this so it looks like a leader board:
`[['25356767', 'tom'],
['443388', 'jin'],
['6744', 'trev'],
['4666', 'ryan'],
['2445', 'jones'],
['536', 'sue'],
['34', 'bob'],
['8', 'hera'],
['1', 'bill'],
['0', 'v']]`
I hope that explains my question.
Can't do that, sorry.
What you're asking to do is, essentially, altering the way the console outputs lists. Simpler (and, probably, prettier) would be to define a function to pretty print the lists.
If you did something like:
def pretty(inlist):
for score, name in inlist:
print name.rjust(10) +"| " +score
Then it would print every line in a pretty format.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a dictionary like:
{'6400': {'6401': '1.0', '6407': '0.3333333333333333', '6536': '0.0', '6448': '0.0'}}
And I would like to product a structure similar to preferably in Pyspark:
('6400',['6400','6401','1.0'])
('6400',['6400','6407','0.3333333333333333'])
('6400',['6400','6536','0.0'])
('6400',['6400','6448','0.0'])
If you do this in python you can use following code to produce the structure you want.
d = {'6400': {'6401': '1.0', '6407': '0.3333333333333333', '6536':
'0.0', '6448': '0.0'}}
result = []
for outer_e in d:
for inner_e in d[outer_e]:
e = [outer_e, inner_e, d[outer_e][inner_e]]
e = (outer_e, e)
result.append(e)
Little bit bulky, but another way to solve problem:
In [1]: d = {'6400': {'6401': '1.0', '6407': '0.3333333333333333', '6536': '0.0'
...: , '6448': '0.0'}}
In [2]: map(lambda item: [(item[0], [item[0], *i]) for i in item[1].items()], d.items())
Out[2]: <map at 0x104563e48>
In [3]: list(_)
Out[3]:
[[('6400', ['6400', '6401', '1.0']),
('6400', ['6400', '6407', '0.3333333333333333']),
('6400', ['6400', '6536', '0.0']),
('6400', ['6400', '6448', '0.0'])]]
And since it unordered dict object, you can't rely on order.