w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Assigning variables in a loop in Python
I don't exactly understand what you're trying to do, but the expression you have above will store the words in a list, it is not a dictionary. You could actually: print('the words in this synset are ' + word[0] + ',' + word[1]) Note that you need to use [] and not () as you write above. More elegant would be the following: print ("the words in this synset are {0}".format(", ".join(word))) because that works with an unknown number of words.

Categories : Python

Assigning variables from inputs in FOR loop in python
def main(): coins = {} for kind in ['5c','10c','20c','50c','$1','$2']: coins[kind] = int(raw_input("Enter the number of " + kind + " coins you wish use: ").strip() or 0)

Categories : Python

Python - assigning values to n variables in a for loop
Anytime you ask yourself how you could create dynamic variables, the answer is "use a dictionary". l=dict() for i in range(n): k='row%d'%(i,) l[k] = map(int, raw_input().split())

Categories : Python

Python list comprehension with multiple variables
Here is one option: L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11), (11, 12, 13, 14, 15, 16)] multiple_index = [(entry[0], entry[3], entry[4]) for entry in L] Or using operator.itemgetter(): from operator import itemgetter indices = itemgetter(0, 3, 4) multiple_index = [indices(entry) for entry in L]

Categories : Python

Python lists without assigning variables
extend doesn't return a value. Thus, printing a.extend(b) will be None. Thus, if you have a = [5, 6, 7, 8, 9].extend(range(15, 20)) and print a it will show None. A way around it would be to concatenate lists a = [5, 6, 7, 8, 9] + range(15, 20) [5, 6, 7, 8, 9][2] - everything is as should be as it starts counting elements from 0. It is not modifying list, it is merely returning a certain element from the list. [5, 6, 7, 8, 7].count(7) and [5, 6, 7, 8, 7].index(8) show the expected output. First one is the number of times 7 occurs in the list, second one is an index of number 8 (again, counting starts from 0). So, all in all the use of hardcoded list behaves as expected in all of the examples you've produced.

Categories : Python

Variables while reading a file with multiple rows in a list - python or shell
Try myfile = open('input','r') link = dict() for line in myfile: line = line.split(",") IDs = line[1].split() link[line[0]]=IDs myfile.close() for name in link.keys(): for ID in link[name]: print ''.join(["www.whatever.com/",name,"/",ID])

Categories : Python

Assigning multiple global variables in JavaScript with one function
function getBackList(urlName, globalVariableName) { $.ajax({ type: "GET", url: urlName, }).done(function (returned_data) { window[globalVariableName] = $.parseJSON(returned_data); }); } Pass in the global variable's name instead ^^^

Categories : Javascript

Assigning variables using choices in TKInter dropdown menu - Python 2.7
Try following code. Read a comment I added. from Tkinter import * import Tkinter as ttk from ttk import * root = Tk() root.title("Age Selector") mainframe = Frame(root) mainframe.grid(column=0,row=0, sticky=(N,W,E,S) ) mainframe.columnconfigure(0, weight = 1) mainframe.rowconfigure(0, weight = 1) mainframe.pack(pady = 10, padx = 10) var = StringVar(root) # Use dictionary to map names to ages. choices = { 'Bob': '35', 'Garry': '45', 'John': '32', 'Hank': '64', 'Tyrone': '21', } option = OptionMenu(mainframe, var, *choices) var.set('Bob') option.grid(row = 1, column =1) Label(mainframe, text="Age").grid(row = 2, column = 1) age = StringVar() # Bind age instead of var age_ent = Entry(mainframe, text=age, width = 15).grid(column =

Categories : Python

Assigning values to list in python
There is a list construct baked right into the core of Python, below is a pretty good introduction: http://www.tutorialspoint.com/python/python_lists.htm You could re-write the code above pretty much identically in python, just changing the syntax from C++ to python. However, there may be a more pythonic way of doing what you require, it is hard to say without having more context around the code. while i < r and j < u: if a[i] <= a[j]: b[k] = a[i] i += 1 # No increment operator in python else: b[k] = a[j] j += 1 k += 1

Categories : Python

Assigning a list during recursive function in Python
You can't change an iterable while using it to drive an iteration, but you could easily make an iterable to hold your results and pass it in to the recursive function as an argument: results = [] def recurse(level, results): level += 1 results.append(level) if level < 10: recurse(level, results) print recurse(0, results) >>> [1,2,3,4,5,6,7,8,9,10] but in this example you could not do for item in results: recurse (item, results)

Categories : Python

Two-dimensional list wrongly assigning values in python
This is explained in the FAQ, under How do I create a multidimensional list? The problem is in this part of the code: board = [] for i in range(7): board.append(line) You're creating a list with 7 references to the same list, line. So, when you modify one, the others all change, because they're the same list. The solution is to create 7 separate lists, like this: def createBoard(self): board = [] for i in range(7): line = [] for i in range(7): line.append(' ') board.append(line) return board Or, more simply, make separate copies of the original list: def createBoard(self): line = [] for i in range(7): line.append(' ') board = [] for i in range(7): board.append(line[:]) return board While we

Categories : Python

C++: Multiple exit conditions in for loop (multiple variables): AND -ed or OR -ed?
The comma operator will return the value of the right expression, so writing this: src < 8, dst >= 0; As a condition will be the same as just writing dst >= 0. The src < 8 will be completely ignored in this case, as it's evaluated separately from the second condition, and then the second condition is returned. This doesn't evalute to AND or to OR, but in fact just has the effect of "throwing away" the first check entirely. If you want to evaluate this correctly, you should use one of your two options (explicitly specifying the behavior via || or &&). For details, see Comma Operator: When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.

Categories : C++

Python 3+ - for in range loop, multiply, product, list NOT using mul or lambda or for in loop
The idea is pretty much the same as for in. Note that you don't need to make a variable from the list length, also you don't need to specify a start for the range(), it's 0 by default. def prod(L): p = 1 for i in range(len(L)): p *= L[i] return p print(prod([1,2,3,4])) # prints 24

Categories : Python

Python Pass multiple variables through command to change multiple lines in a text file with regex
I replaced the for loop with the following code and it worked: with open('test1.txt') as f: line1 = f.readline() line2 = f.readline() line3 = f.readline() build = re.sub ('build='r'.*','build='+buildpath,line1) apps = re.sub ('apps='r'.*','apps='+appspath,line2) logs = re.sub ('logs='r'.*','logs='+logspath,line3) tf.write(build + apps + logs)

Categories : Python

bash script loop multiple variables
You can use arrays for that: A=({a..z}) B=({1..26}) for (( I = 0; I < 26; ++I )); do echo "/dev/sd${A[I]} /disk${B[I]} ext4 noatime 1 1" >> test done Example output: /dev/sda /disk1 ext4 noatime 1 1 ... /dev/sdz /disk26 ext4 noatime 1 1 Update: As suggested you could just use the index for values of B: A=('' {a..z}) for (( I = 1; I <= 26; ++I )); do echo "/dev/sd${A[I]} /disk${I} ext4 noatime 1 1" >> test done Also you could do some formatting with printf to get a better output, and cleaner code: A=('' {a..z}) for (( I =

Categories : Bash

Longer than intended loop due to multiple variables
Although this is only a guess without seeing your actual indented code, I believe your problem is this: while 0 <= px <= width: while 0 <= py <= height: # a whole mess of logic If py goes out of bounds, you'll escape the inner loop, but then just keep repeating that inner loop until px also goes out of bounds. If px goes out of bounds, you'll still be stuck inside the inner loop until py also goes out of bounds. What you want is to escape as soon as either goes out of bounds. In other words, you want a single loop, that keeps going as long as both are in bounds. Which you can translate directly from English to Python: while 0 <= px <= width and 0 <= py <= height: # same whole mess of logic

Categories : Python

Python: How to use a for-loop or while-loop to alphabetize a list in a file
If insertion_sort worked before, I guess it works now, too. The problem is that usfl contains only one element, the content of the file. If you have a fruit on each line, you can use this to populate your list: usfl = [line.rstrip () for line in unsorted_fruits] or if it is a comma separated list, you can use: usfl = unsorted_fruits.read ().split (',')

Categories : Python

How to reset some function variables in Python in a loop
Just store the old functions in a dictionary: old = {'a': a, 'b': b, 'c': c} then use the globals() dictionary to restore them: globals().update(old) This only works if a, b and c were globals to begin with. You can use the same trick to assign d to all those names: globals().update(dict.fromkeys(old.keys(), d)) This sets the keys a, b and c to the same value d.

Categories : Python

How to create ForEach loop to go through multiple variables Powershell
Give this a try, I can't test it using label & textbox object but it can work tuning it better: 1..8 | ForEach-Object { IF ( (iex "`$Label$_.Text.Length") -ne 0 ) { iex "`$Label$_.Visible = `$true" iex "`$TextBox$_.Visible = `$true" iex "`$TextBox$_.Text = 'Enter new name for ' + `$Label$_.Text" } }

Categories : Powershell

Python: How to return a list without modifying the original list using a while loop only?
If you need to do this with a while loop, you could do it by appending each element to a list rather than printing it, and then returning that list: def everythird(l): i = 0 ret = [] while i < len(l): ret.append(l[i]) i += 3 return ret Though as you note, it would certainly be preferably to do def everythird(l): return l[0::3] Or if you were allowed to use a for loop: def everythird(l): ret = [] for i in range(0, len(l), 3): ret.append(l[i]) return ret Finally, if you were allowed to use a list comprehension: def everythird(l): return [l[i] for i in range(0, len(l), 3)] The slice indexing is certainly the best, but in any case a while loop might be the worst way to do it.

Categories : Python

List comprehension/list creating loop in python 3.x
bakeries = ['a','b','c'] breadtypes = ['flat','rye','white'] results = [] for i in bakeries: print('How many of each type of bread for {0}:'.format(i)) number_of_types = [] for bread in breadtypes: number_of_types.append(input('{0}:'.format(bread))) results.append(number_of_types) for k,v in enumerate(bakeries): print('Here are the different types of breads for {0}'.format(v)) print(''.join('{0}:{1}'.format(a,b) for a,b in zip(breadtypes, results[k])))

Categories : Python

Python nested for loop to split a file into lines then each line into variables
with open('data.txt', 'r') as data: for _input in data: line = _input.split(' ') data = {'Index':line[0], 'Origin Time':line[-3:][-1].strip() } data.update(dict(zip(line[1:-3][0::2], line[1:-3][1::2]))) print data

Categories : Python

List entries to variables: ttk python
Here is a way to rotate the characters in a string around, assuming there are only A-Z letters in your string. string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i in range(10): string = "".join([chr((ord(letter) - ord('A') + 1) % 26 + ord('A')) for letter in string]) print string The idea is that each letter has an ASCII code difference from the letter A. So letter A would be 0, letter B is 1. When letter Z is shifted forward, it needs to go back to A. This is where the modulo (%) comes in, it shifts the letter Z back to A if needed. Output: BCDEFGHIJKLMNOPQRSTUVWXYZA CDEFGHIJKLMNOPQRSTUVWXYZAB DEFGHIJKLMNOPQRSTUVWXYZABC EFGHIJKLMNOPQRSTUVWXYZABCD FGHIJKLMNOPQRSTUVWXYZABCDE GHIJKLMNOPQRSTUVWXYZABCDEF HIJKLMNOPQRSTUVWXYZABCDEFG IJKLMNOPQRSTUVWXYZABCDEFGH JKLMNOPQRSTUVWXYZABCDEFGHI KLMN

Categories : Python

Can I get a list of the variables that reference an other in Python 2.7?
Yes, and no. You can get a list of global variables: for name, val in globals().items(): if val is obj: yield name You can also get a list of local variables: for name, val in locals().items(): if val is obj: yield name However, you will with this miss all variables in other contexts than local to your function or global to the module. You can find variables in calling contexts with frame-magic, but you won't be able to find anything that is global to other modules, for example. What you would use this for, I don't know. You will also not find any attributes that reference the object, but attributes aren't variables so maybe that's OK. You can get all objects that reference your object though. And that will include the globals and locals for all the functio

Categories : Python

iterating list of array-list and assigning each list to single dynamically created div in jsp
Try this, <c:forEach var="user" items="${userList}" varStatus="count"> <div id="col${count}"> <c:out value="${user.name}"/> </div> </c:forEach>

Categories : Java

Python list.remove for loop "x not in list"
your list is not 2000 long, you start at 2.. >>> primes=list(range(2,2001)) >>> print len(primes) 1999 So when you do the while loop, it doesn't get up to 2000... :)

Categories : Python

If I want to list multiple variables in one 'if' command in unix, how would I do it? [Beginner]
-a is the AND operator in test: if [ -n "$variableA" -a -n "$variableB" -a -n "$variableC" -a "$variableD" -eq 1 ] then echo "Bye bye" fi If you want OR, the operator is -o. These are both in the test man page.

Categories : Unix

Is there a way to initialize multiple variables from array or List in Scala?
How about this: scala> val numbers = List(1, 2, 3) numbers: List[Int] = List(1, 2, 3) scala> val List(hours, minutes, seconds) = numbers hours: Int = 1 minutes: Int = 2 seconds: Int = 3

Categories : Scala

How to return multiple variables from python to bash
From your python script, output one variable per line. Then from you bash script, read one variable per line: Python print "foo bar" print 5 Bash #! /bin/bash python main.py | while read line ; do echo $line done Final Solution: Thanks Guillaume! You gave me a great starting point out the soultion. I am just going to post my solution here for others. #! /bin/bash array=() while read line ; do array+=($line) done < <(python main.py) echo ${array[@]} I found the rest of the solution that I needed here

Categories : Python

Using class to define multiple variables in python
A method in Python is a function. If you want to get a value from a member function you have to end it with (). That said, some refactoring may help eliminate boilerplate and reduce the problem set size in your head. I'd suggest using a @property for some of these things, combined with a slight refactor class variable: def __init__(self, length): self.length = length # time length` @property def state_dynamic(self): return self.np_length @property def state_static(self): return self.np_length @property def control_dynamic(self): return self.np_length @property def control_static(self): return self.np_length @property def scheduling(self): return self.np_length @property def np_length(self): return np.zeros(2, np.size(self.length)) That way you can us

Categories : Python

Print multiple variables in one line using python
There are a number of ways that you could go about this. The simplest is probably to initialize an empty string before the if statements. Then, instead of printing split[1] and ip[2], concatenate them to the empty string and print that afterwards. So it would look something like this: printstr = "" if re.search... ... printstr += "Label for first item " + split[1] + ", " if re.search... ... printstr += "Label for second item " + ip[2] print printstr

Categories : Python

Python augmenting multiple variables inline
You cannot use an augmented assignment statement on multiple targets, no. Quoting the augmented assignment documentation: With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations. Emphasis mine. In-place augmented assignment is translated from target -= expression to target = target.__isub__(expression) (with corresponding __i...__ hooks for each operator) and translating that operation to multiple targets is not supported. Under the hood, augmented assignment is a specialisation of the bina

Categories : Python

Python list of class: variables "aliased", no sub-reference possible
You are creating one instance, then copying the reference to that instance nlst times: dlst = [Myclass(0)]*nlst This does not create a list of nlist instances of Myclass(0); it creates a list of nlst references, all pointing to one object. Use a list comprehension instead: dlst = [Myclass(0) for _ in range(nlst)] In a list comprehension, the expression on the left is re-executed for each iteration of the loop.

Categories : Python

Assigning variables to Strings
Short answer: what you want is strncpy Long answer: In defining name as a character array in a struct, you are allocating a set amount of memory in that struct to store the characters in the name. To move characters into that space, you have to copy them, and that's where strncpy comes in. You could also have defined name as a pointer to char (char *), in which case your assignments would make sense. In C, when you use a literal string, you're really including those bytes somewhere within your executable, and that "..." syntax returns the pointer to where those characters are statically stored, as a char *. From a type standpoint, char * is a less specific type than char[30], and so you cannot directly assign that pointer into your player.name variable. From a C implementation standpoint

Categories : C++

Re-assigning String variables
You'll want to use an ArrayList if you need to store the data. An ArrayList is just like an array, except that it grows dynamically as you add elements to it. Define it with: List<String> myList = new ArrayList<String>(); Then as the user enters something, write myList.add(someStringVariable);

Categories : Java

Shorthand for assigning variables
TypeScript will allow you to cast the item in this case... although this means that test1 and test2 are the same object. interface Foo1 { a: string; b: boolean c: Object; } interface Foo2 extends Foo1 { d: number; } var test1: Foo1 = { a: '...', b: true, c: {} }; var test2: Foo2 = <Foo2> test1; test2.d = 1; If you want a copy, not the same object, you can create a method to copy the object's properties. Here is an example of a copy: var test1: Foo1 = { a: '...', b: true, c: {} }; var test2: Foo2 = <Foo2>{}; for (var variable in test1) { if( test1.hasOwnProperty( variable ) ) { test2[variable] = test1[variable]; } } With a little hint of generics, you can encapsulate this in a static helper method, like this: class ObjectHelper { st

Categories : Typescript

conditionally adding multiple items to a list of lists via python list comprehension
The line html = BeautifulSoup(urllib2.urlopen('http://domain.com').read(), 'lxml') implies you have lxml installed, so you could use an XPath using | to pull out text or attribute values: import urllib2 import lxml.html as LH html = LH.parse(urllib2.urlopen('http://domain.com')) clean_data = [[elt for elt in tr.xpath('td/a/text() | td/a/@href | td/text()')] for tr in html.xpath('//table[@id="targeted_table"]/tr')] print(clean_data) yields [['http://domain.com', 'data 01', 'data 02', 'data 03', 'data 04'], ['http://domain.com', 'data 11', 'data 12', 'data 13', 'data 14'], ['http://domain.com', 'data 01', 'data 22', 'data 23', 'data 24'], ['http://domain.com', 'data 01', 'data 32', 'data 33', 'data 34']] You could also do it with a single call to the xpath met

Categories : Python

Passing multiple variables from dropdowns using Django/Python
request.GET in your view is a dictionary; by doing request.GET['search3'] you're just accessing the value of its search3 key. So in your template, you should be able to just add other <select> elements with their own names and retrieve their submitted values from request.GET in the same way.

Categories : Python

Python cluster variables in list of tuples by 2 factors silmutanously
You can second time use your parse method for results from first running. In this case you will receive not exactly the same you want but very similar: def stat(lst, index): """Calculate mean and std deviation from the input list.""" n = float(len(lst)) mean = sum([pair[index] for pair in lst])/n stdev = sqrt((sum(x[index]*x[index] for x in lst) / n) - (mean * mean)) return mean, stdev def parse(lst, n, index): cluster = [] for i in lst: if len(cluster) <= 1: # the first two values are going directly in cluster.append(i) continue mean, stdev = stat(cluster, index) if (abs(mean - i[index]) > n * stdev): # check the "distance" yield cluster cluster[:] = [] # reset cluster to th

Categories : Python

Do I need to use locks when simply assigning variables?
You have to remember the thread could also be looking at a stale copy, by locking you assure that the version of the variable you are looking at is being refreshed When I first started coding and thought that maybe I don't need the freshest copy of the variable I would get stuck in infinite loops because I assume the variable would be updated eventually, but if the variable was cached then it would never update I included examples with brief descriptions, don't worry about the way the thread is started, that is not relevant private static bool _continueLoop = true; private static readonly object _continueLoopLock = new object(); private static void StopLoop() { lock(_continueLoopLock) _continueLoop = false; } private static void ThreadALoopWillGetStales() { while(_c

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.