python nested loop list - python
I am currently stuck at one nested loop problem. I would appreciate it greatly if anyone can offer their insight or tips on how to solve this sticky problem that i am facing.
I am trying to append some values to a list in a for loop. I succeeded in doing that. But how can I get the last list as my variable to use in another loop?
Lets say. I am extracting something by appending them in a list in a for loop.
a=list()
for b in hugo:
a.append(ids)
print(a)
gives me
[1]
[1,2]
[1,2,3]
[1,2,3,4]
But I only need the last line of the list as my variable to be used in another for loop. Can anybody gives me some insights how to do this? Your help is much appreciated. Thanks in advance.
Edit:
Actually I am not trying to get someone to do my homework for me. I am just testing some software programming using python. Here goes:
I am trying to write a script to extract files with the end name of .dat from ANSA pre-processor with the correct name and file ID
For example:
ID Name
1 hugo1.dat
8 hugo2.dat
11 hugo3.dat
18 hugo4.dat
Here is what I have written:
import os
import ansa
from ansa import base
from ansa import constants
from ansa import guitk
def export_include_content():
directory = gutik.UserInput('Please enter the directory to Output dat files:')
ishow=list()
includes=list()
setna=list()
iname=list()
# Set includes variables to collect the elements from a function known as "INCLUDE" from the software
includes=base.CollectEntitites(deck, None, "INCLUDE")
# For loop to get information from the "INCLUDE" function with the end filename ".dat"
for include in includes:
ret=base.GetEntityCardValues(deck, include, 'NAME', 'ID')
ids=str(ret['ID'])
setname=ret['NAME']
if setname.endswith('dat'):
ishow.append(ids)
iname.append(setname)
# Print(ishow) gives me
[1]
[1,8]
[1,8,11]
[1,8,11,18]
# print(iname) gives me
[hugo1]
[hugo1,hugo2]
[hugo1,hugo2,hugo3]
[hugo1,hugo2,hugo3,hugo4]
# Now that I got both of my required list of IDs and Names. It's time for me to save the files with the respective IDs and Names.
for a in ishow:
test=base.GetEntity(deck,'INCLUDE',int(a))
print(a)
file_path_name=directory+"/"+iname
print(file_path_name)
#print(a) gives me
1
8
11
18
#print(file_path_name) gives me
filepath/[hugo1,hugo2,hugo3,hugo4]
filepath/[hugo1,hugo2,hugo3,hugo4]
filepath/[hugo1,hugo2,hugo3,hugo4]
filepath/[hugo1,hugo2,hugo3,hugo4]
# This is the part I got stuck. I wanted the output to be printed in this order:
1
filepath/hugo1
8
filepath/hugo2
11
filepath/hugo3
18
filepath/hugo4
But it doesnt work well so far for me, that's why I am asking whether you all can provide me some assistance on solving this problem :) Helps appreciated!! Thanks all
Your problem is with the code indent:
a=list()
for b in hugo:
a.append(ids)
print(a)
Use a dictionary instead of having 2 separate list for ids and names of includes
The code below creates a dictionary with include id as keys and the corresponding include's name as the value. later this dict is used to print file name
In case you want to save each include as separate file,First isolate the include using "Or"(API) then we have an API for each deck in ANSA to do save files(make sure to enable optional argument 'save visible').for example for NASTRAN it is OutputNastran you can search it in the API search tab in the script editor window
dict={}
for include in includes:
ret=base.GetEntityCardValues(deck, include, 'NAME', 'ID')
ids=str(ret['ID'])
setname=ret['NAME']
if setname.endswith('.dat'):
dict[ids]=setname
for k, v in dict.items():
test=base.GetEntity(deck,'INCLUDE',int(k))
file_path_name=directory+"/"+v
print(file_path_name)
Hope this helps
Assuming ids is actually just the elements in hugo:
a=[id for id in hugo]
print(a)
Or
a=hugo.copy()
print(a)
Or
print(hugo)
Or
a=hugo
print(a)
Or
string = "["
for elem in hugo:
string.append(elem + ",")
print(string[:-1] + "]")
Edit: Added more amazing answers. The last is my personal favourite.
Edit 2:
Answer for your edited question:
This part
for a in ishow:
test=base.GetEntity(deck,'INCLUDE',int(a))
print(a)
file_path_name=directory+"/"+iname
print(file_path_name)
Needs to be changed to
for i in range(len(ishow)):
test=base.GetEntity(deck,'INCLUDE',int(ishow[i]))
file_path_name=directory+"/"+iname[i]
The print statements can be left if you wish.
When you are trying to refer to the same index in multiple lists, it is better to use for i in range(len(a))so that you can access the same index in both.
Your current code has the loop printing every single time it iterates through, so move the print statement left to the same indent level as the for loop, so it only prints once the for loop has finished running its iterations.
a=list()
for b in hugo:
a.append(ids)
print(a)
Related
How to print specific json data for multiple instances?
import requests url = "https://api.gametools.network/bf1/players/?gameId=7218126050214" r = requests.get(url) data = r.json() print(data['teams'][1]['players'][0]['name']) print(data['teams'][1]['players'][1]['name']) print(data['teams'][1]['players'][2]['name']) print(data['teams'][1]['players'][3]['name']) print(data['teams'][1]['players'][4]['name']) print(data['teams'][1]['players'][5]['name']) print(data['teams'][1]['players'][6]['name']) print(data['teams'][1]['players'][7]['name']) print(data['teams'][1]['players'][8]['name']) print(data['teams'][1]['players'][9]['name']) print(data['teams'][1]['players'][10]['name']) print(data['teams'][1]['players'][11]['name']) print(data['teams'][1]['players'][12]['name']) print(data['teams'][1]['players'][13]['name']) print(data['teams'][1]['players'][14]['name']) print(data['teams'][1]['players'][15]['name']) print(data['teams'][1]['players'][16]['name']) print(data['teams'][1]['players'][17]['name']) print(data['teams'][1]['players'][18]['name']) print(data['teams'][1]['players'][19]['name']) print(data['teams'][1]['players'][20]['name']) This is a snippet of my code that I think could be really improved to save some space, the issue is I can't seem to find a way to enumerate all the players name beside doing them one per one like shown above, my goal is to have a list that will show every username for both team of a given server. I should mention the code is currently working but I feel like there is a much simpler way to obtain the data I need, I did search for these methods but because my data is nested in a list/dictionary I get confused. Any suggestion is welcome, thank you :)
Here is how to iterate over a list: l = [1, 2, 3, 4] for element in l: print(l) Once you know that, it's only a matter of breaking nested iteration problems down to their simplest form above. So you just need to get the list which you need to iterate over, and then use the above sample you already know: l = data['teams'][1]['players'] for element in l: print(element['name'])
Let's write a simple function that accepts the data from a team and use a for loop to iterate over the players. def printTeamNames(team): print(team["teamid"]) for player in team["players"]: print(player["name"]) Then we can pass that function that data for each team. printTeamNames(data["teams"][0]) printTeamNames(data["teams"][1])
can someone explain to me what I did wrong?
I need help unscrambling this code. I am only allowed to use these specific lines of code, but I need to 'unscramble' it to make it work. To me, this code looks good but I don't seem to get it to work so I would like to find out why this is the case. The assignment that I am trying to solve is as follows: Read in the file using the csv reader and build a dictionary with the tree species as the key and a count of the number of times the tree appears. Use the "in" operator to see if a tree has been added, and if not set it to 1. Print the dictionary with the counts at the end. My code is as follows: from BrowserFile import open as _ import csv with open("treeinventory.csv", "r", newline='') as f: count = {} reader = csv.reader(f) for yard in reader: for tree in yard: if tree in count: count[tree] = 1 else: count[tree] = count[tree] + 1 print(count) I would love if someone can help me and also explain why this code is not able to work as it is, i am trying to learn and this would be very helpful! thank you!
Generally, we don't solve "homework" problems on SO. You should also try to ask specific questions. Also put better titles on your questions. And, as such, I always like to post This to help new question askers out. Since I'm here: The answer to your assignment is that line 9 and line 11 are swapped. This is because the logic seems to set that dict count with the key tree is being set to 1 if the key is in the dict, and add 1 to the value stored at count[tree] if it's not in the dict. This will result in a KeyError exception to be thrown when the value is accessed to do this addition in the statement count[tree] + 1, because, there is no value there yet. Of course, without the input file, I can't actually run the code to verify it, so please try this out for yourself and update your question with specific issues if any come up.
Python- Insert new values into 'nested' list?
What I'm trying to do isn't a huge problem in php, but I can't find much assistance for Python. In simple terms, from a list which produces output as follows: {"marketId":"1.130856098","totalAvailable":null,"isMarketDataDelayed":null,"lastMatchTime":null,"betDelay":0,"version":2576584033,"complete":true,"runnersVoidable":false,"totalMatched":null,"status":"OPEN","bspReconciled":false,"crossMatching":false,"inplay":false,"numberOfWinners":1,"numberOfRunners":10,"numberOfActiveRunners":8,"runners":[{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":2.8,"size":34.16},{"price":2.76,"size":200},{"price":2.5,"size":237.85}],"availableToLay":[{"price":2.94,"size":6.03},{"price":2.96,"size":10.82},{"price":3,"size":33.45}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832765}... All I want to do is add in an extra field, containing the 'runner name' in the data set below, into each of the 'runners' sub lists from the initial data set, based on selection_id=selectionId. So initially I iterate through the full dataset, and then create a separate list to get the runner name from the runner id (I should point out that runnerId===selectionId===selection_id, no idea why there are multiple names are used), this works fine and the code is shown below: for market_book in market_books: market_catalogues = trading.betting.list_market_catalogue( market_projection=["RUNNER_DESCRIPTION", "RUNNER_METADATA", "COMPETITION", "EVENT", "EVENT_TYPE", "MARKET_DESCRIPTION", "MARKET_START_TIME"], filter=betfairlightweight.filters.market_filter( market_ids=[market_book.market_id], ), max_results=100) data = [] for market_catalogue in market_catalogues: for runner in market_catalogue.runners: data.append( (runner.selection_id, runner.runner_name) ) So as you can see I have the data in data[], but what I need to do is add it to the initial data set, based on the selection_id. I'm more comfortable with Php or Javascript, so apologies if this seems a bit simplistic, but the code snippets I've found on-line only seem to assist with very simple Python lists and nothing 'nested' (to me the structure seems similar to a nested array). As per the request below, here is the full list: {"marketId":"1.130856098","totalAvailable":null,"isMarketDataDelayed":null,"lastMatchTime":null,"betDelay":0,"version":2576584033,"complete":true,"runnersVoidable":false,"totalMatched":null,"status":"OPEN","bspReconciled":false,"crossMatching":false,"inplay":false,"numberOfWinners":1,"numberOfRunners":10,"numberOfActiveRunners":8,"runners":[{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":2.8,"size":34.16},{"price":2.76,"size":200},{"price":2.5,"size":237.85}],"availableToLay":[{"price":2.94,"size":6.03},{"price":2.96,"size":10.82},{"price":3,"size":33.45}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832765},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":20,"size":3},{"price":19.5,"size":26.36},{"price":19,"size":2}],"availableToLay":[{"price":21,"size":13},{"price":22,"size":2},{"price":23,"size":2}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832767},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":11,"size":9.75},{"price":10.5,"size":3},{"price":10,"size":28.18}],"availableToLay":[{"price":11.5,"size":12},{"price":13.5,"size":2},{"price":14,"size":7.75}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832766},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":48,"size":2},{"price":46,"size":5},{"price":42,"size":5}],"availableToLay":[{"price":60,"size":7},{"price":70,"size":5},{"price":75,"size":10}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832769},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":18.5,"size":28.94},{"price":18,"size":5},{"price":17.5,"size":3}],"availableToLay":[{"price":21,"size":20},{"price":23,"size":2},{"price":24,"size":2}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832768},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":4.3,"size":9},{"price":4.2,"size":257.98},{"price":4.1,"size":51.1}],"availableToLay":[{"price":4.4,"size":20.97},{"price":4.5,"size":30},{"price":4.6,"size":16}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832771},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":24,"size":6.75},{"price":23,"size":2},{"price":22,"size":2}],"availableToLay":[{"price":26,"size":2},{"price":27,"size":2},{"price":28,"size":2}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832770},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":5.7,"size":149.33},{"price":5.5,"size":29.41},{"price":5.4,"size":5}],"availableToLay":[{"price":6,"size":85},{"price":6.6,"size":5},{"price":6.8,"size":5}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":10064909}],"publishTime":1551612312125,"priceLadderDefinition":{"type":"CLASSIC"},"keyLineDescription":null,"marketDefinition":{"bspMarket":false,"turnInPlayEnabled":false,"persistenceEnabled":false,"marketBaseRate":5,"eventId":"28180290","eventTypeId":"2378961","numberOfWinners":1,"bettingType":"ODDS","marketType":"NONSPORT","marketTime":"2019-03-29T00:00:00.000Z","suspendTime":"2019-03-29T00:00:00.000Z","bspReconciled":false,"complete":true,"inPlay":false,"crossMatching":false,"runnersVoidable":false,"numberOfActiveRunners":8,"betDelay":0,"status":"OPEN","runners":[{"status":"ACTIVE","sortPriority":1,"id":10064909},{"status":"ACTIVE","sortPriority":2,"id":12832765},{"status":"ACTIVE","sortPriority":3,"id":12832766},{"status":"ACTIVE","sortPriority":4,"id":12832767},{"status":"ACTIVE","sortPriority":5,"id":12832768},{"status":"ACTIVE","sortPriority":6,"id":12832770},{"status":"ACTIVE","sortPriority":7,"id":12832769},{"status":"ACTIVE","sortPriority":8,"id":12832771},{"status":"LOSER","sortPriority":9,"id":10317013},{"status":"LOSER","sortPriority":10,"id":10317010}],"regulators":["MR_INT"],"countryCode":"GB","discountAllowed":true,"timezone":"Europe\/London","openDate":"2019-03-29T00:00:00.000Z","version":2576584033,"priceLadderDefinition":{"type":"CLASSIC"}}}
i think i understand what you are trying to do now first hold your data as a python object (you gave us a json object) import json my_data = json.loads(my_json_string) for item in my_data['runners']: item['selectionId'] = [item['selectionId'], my_name_here] the thing is that my_data['runners'][i]['selectionId'] is a string, unless you want to concat the name and the id together, you should turn it into a list or even a dictionary each item is a dicitonary so you can always also a new keys to it item['new_key'] = my_value
So, essentially this works...with one exception...I can see from the print(...) in the loop that the attribute is updated, however what I can't seem to do is then see this update outside the loop. mkt_runners = [] for market_catalogue in market_catalogues: for r in market_catalogue.runners: mkt_runners.append((r.selection_id, r.runner_name)) for market_book in market_books: for runner in market_book.runners: for x in mkt_runners: if runner.selection_id in x: setattr(runner, 'x', x[1]) print(market_book.market_id, runner.x, runner.selection_id) print(market_book.json()) So the print(market_book.market_id.... displays as expected, but when I print the whole list it shows the un-updated version. I can't seem to find an obvious solution, which is odd, as it seems like a really simple thing (I tried messing around with indents, in case that was the problem, but it doesn't seem to be, its like its not refreshing the market_book list post update of the runners sub list)!
Python - Searching a dictionary for strings
Basically, I have a troubleshooting program, which, I want the user to enter their input. Then, I take this input and split the words into separate strings. After that, I want to create a dictionary from the contents of a .CSV file, with the key as recognisable keywords and the second column as solutions. Finally, I want to check if any of the strings from the split users input are in the dictionary key, print the solution. However, the problem I am facing is that I can do what I have stated above, however, it loops through and if my input was 'My phone is wet', and 'wet' was a recognisable keyword, it would go through and say 'Not recognised', 'Not recognised', 'Not recognised', then finally it would print the solution. It says not recognised so many times because the strings 'My', 'phone' and 'is' are not recognised. So how do I test if a users split input is in my dictionary without it outputting 'Not recognised' etc.. Sorry if this was unclear, I'm quite confused by the whole matter. Code: import csv, easygui as eg KeywordsCSV = dict(csv.reader(open('Keywords and Solutions.csv'))) Problem = eg.enterbox('Please enter your problem: ', 'Troubleshooting').lower().split() for Problems, Solutions in (KeywordsCSV.items()): pass Note, I have the pass there, because this is the part I need help on. My CSV file consists of: problemKeyword | solution For example; wet Put the phone in a bowl of rice.
Your code reads like some ugly code golf. Let's clean it up before we look at how to solve the problem import easygui as eg import csv # # KeywordsCSV = dict(csv.reader(open('Keywords and Solutions.csv'))) # why are you nesting THREE function calls? That's awful. Don't do that. # KeywordsCSV should be named something different, too. `problems` is probably fine. with open("Keywords and Solutions.csv") as f: reader = csv.reader(f) problems = dict(reader) problem = eg.enterbox('Please enter your problem: ', 'Troubleshooting').lower().split() # this one's not bad, but I lowercased your `Problem` because capital-case # words are idiomatically class names. Chaining this many functions together isn't # ideal, but for this one-shot case it's not awful. Let's break a second here and notice that I changed something on literally every line of your code. Take time to familiarize yourself with PEP8 when you can! It will drastically improve any code you write in Python. Anyway, once you've got a problems dict, and a problem that should be a KEY in that dict, you can do: if problem in problems: solution = problems[problem] or even using the default return of dict.get: solution = problems.get(problem) # if KeyError: solution is None If you wanted to loop this, you could do something like: while True: problem = eg.enterbox(...) # as above solution = problems.get(problem) if solution is None: # invalid problem, warn the user else: # display the solution? Do whatever it is you're doing with it and... break
Just have a boolean and an if after the loop that only runs if none of the words in the sentence were recognized.
I think you might be able to use something like: for word in Problem: if KeywordsCSV.has_key(word): KeywordsCSV.get(word) or the list comprehension: [KeywordsCSV.get(word) for word in Problem if KeywordsCSV.has_key(word)]
Use generic keys in dictionary in Python
I am trying to name keys in my dictionary in a generic way because the name will be based on the data I get from a file. I am a new beginner to Python and I am not able to solve it, hope to get answer from u guys. For example: from collections import defaultdict dic = defaultdict(dict) dic = {} if cycle = fergurson: dic[cycle] = {} if loop = mourinho: a = 2 dic[cycle][loop] = {a} Sorry if there is syntax error or any other mistake. The variable fergurson and mourinho will be changing due to different files that I will import later on. So I am expecting to see my output when i type : dic[fergurson][mourinho] the result will be: >>>dic[fergurson][mourinho] ['2'] It will be done by using Python
Naming things, as they say, is one of the two hardest problems in Computer Science. That and cache invalidation and off-by-one errors. Instead of focusing on what to call it now, think of how you're going to use the variable in your code a few lines down. If you were to read code that was for filename in directory_list: print filename It would be easy to presume that it is printing out a list of filenames On the other hand, if the same code had different names for a in b: print a it would be a lot less expressive as to what it is doing other than printing out a list of who knows what. I know that this doesn't help what to call your 'dic' variable, but I hope that it gets you on the right track to find the right one for you.
i have found a way, if it is wrong please correct it import re dictionary={} dsw = "I am a Geography teacher" abc = "I am a clever student" search = re.search(r'(?<=Geography )(.\w+)',dsw) dictionary[search]={} again = re.search(r'(?<=clever )(.\w+)' abc) dictionary[search][again]={} number = 56 dictionary[search][again]={number} and so when you want to find your specific dictionary after running the program: dictionary["teacher"]["student"] you will get >>>'56' This is what i mean to