I've got a list and i've managed to turn the list into strings. Now I want to assign a variable to each item in the list by using string formatting to append a 1 onto the end of the variable.
listOne = ['33.325556', '59.8149016457', '51.1289412359']
itemsInListOne = int(len(listOne))
num = 4
varIncrement = 0
while itemsInListOne < num:
for i in listOne:
print a = ('%dfinalCoords{0}') % (varIncrement+1)
print (str(listOne).strip('[]'))
break
I get the following error: SyntaxError: invalid syntax
How can I fix this and assign a new variable in the format:
a0 = 33.325556
a1 = 59.8149016457 etc.
Your current code has a few issues:
listOne = ['33.325556', '59.8149016457', '51.1289412359']
itemsInListOne = int(len(listOne)) # len will always be an int
num = 4 # magic number - why 4?
varIncrement = 0
while itemsInListOne < num: # why test, given the break?
for i in listOne:
print a = ('%dfinalCoords{0}') % (varIncrement+1) # see below
print (str(listOne).strip('[]')) # prints list once for each item in list
break # why break on first iteration
One line in particular is giving you trouble:
print a = ('%dfinalCoords{0}') % (varIncrement+1)
This:
simultaneously tries to print and assign a = (hence the SyntaxError);
mixes two different types of string formatting ('%d' and '{0}'); and
never actually increments varIncrement, so you will always get '1finalCoords{0}' anyway.
I would suggest the following:
listOne = ['33.325556', '59.8149016457', '51.1289412359']
a = list(map(float, listOne)) # convert to actual floats
You can easily access or edit individual values by index, e.g.
# edit one value
a[0] = 33.34
# print all values
for coord in a:
print(coord)
# double every value
for index, coord in enumerate(a):
a[index] = coord * 2
Looking at your previous question, it seems that you probably want pairs of coordinates from two lists, which can also be done with a simple list of 2-tuples:
listOne = ['33.325556', '59.8149016457', '51.1289412359']
listTwo = ['2.5929778', '1.57945488999', '8.57262235411']
coord_pairs = zip(map(float, listOne), map(float, listTwo))
Which gives:
coord_pairs == [(33.325556, 2.5929778),
(59.8149016457, 1.57945488999),
(51.1289412359, 8.57262235411)]
Related
i am trying to compare an "i" counter whitch is interger with a list whitch inludes str numbers , and add it in a string variable
LPL = ["1","2","3"]
f = str()
for i in range (x):
if str(i) == LPL[i]:
f+=str(i)
i expected the f variable had the result of the comparsion: f = 123
List index starts from 0:
LPL = ["1","2","3"]
s = ""
for i in range(1,len(LPL)+1):
if i == int(LPL[i-1]):
s+=str(i)
print(s)
Note that you should use a range from a number to a number and also that python indexes starts from 0, so you need to adapt the code in a way like:
LPL = ["1","2","3"]
f = str()
for i in range (1, len(LPL)+1):
### note that your LPL[0] == 1 and not LPL[1] == 1, so you need to decreasee a number here, that's why a +1 in the range too
if str(i) == LPL[i-1]:
f+=str(i)
### OUTPUT
>>> f
'123'
Perhaps I missing something, but if you wish to combine the elements of the list, either by conjoining strings or adding integers, consider using reduce:
LPL = ["1","2","3"]
LPL2 = [1,2,3]
f = reduce(lambda a,b : a+b, LPL) # "123"
f_int = reduce(lambda a,b : a+b, LPL) # 6
I can print the following list of lists fine, but when I append to an empty list, it skips the last on each iteration or gives me an index out of range error when I add one more.
This works:
ordered_results = []
temp = []
A = len(results[1])-2
i = 1
while i < len(results):
x = 0
y = 1
while x < A:
temp = [results[i][0], results[0][x], results[i][y]]
print(temp)
x+=1
y+=1
temp = [results[i][0], results[0][x], results[i][y]]
print(temp)
i+=1
ordered_results
Note: len(results[0]) = 240 and len(results[1] = 241
If you replace "print" with ordered_results.append(temp) it skips:
results[i][0], results[0][239], results[i][240]
each iteration.
(Note the code was expanded as I am messing around trying to figure this out, it was more compact before).
I have a exercise ,Input data will contain the total count of pairs to process in the first line.
The following lines will contain pairs themselves - one pair at each line.
Answer should contain the results separated by spaces.
My code:
n = int(raw_input())
sum = 0
for i in range(n):
y = raw_input().split(" ")
for i in y:
sum = sum + int(i)
print sum
With my code , I come the Sum together, but I will that the results to come separated by spaces . Thanks for yours help .
with your current code what you get is the total sum of all the given numbers, to get the sum per line you need to initialize your counter in the outer loop, and then print it, and as you want to print all it in the same line there are several ways to do it, like save it in a list or telling print that don't print a new, line which is done by adding a , at the end like print x, with that in mind then the changes needed are
n = int(raw_input())
for i in range(n):
pairs = raw_input().split() #by default split use spaces
pair_sum = 0
for p in pairs:
pair_sum += int(p) # a += b is the same as a = a + b
print pair_sum,
print "" # to print a new line so any future print is not done in the same line as the previous one
that was the version with print per line, next is the version using list
n = int(raw_input())
resul_per_line = []
for i in range(n):
pairs = raw_input().split() #by default split use spaces
pair_sum = 0
for p in pairs:
pair_sum += int(p) # a += b is the same as a = a + b
resul_per_line.append( str(pair_sum) ) #conver each number to a string to use with join bellow
print " ".join(resul_per_line)
with either of the above let said for example that the input data is
3
1 2
40 50
600 700
then the result would be
3 90 1300
some parts of the above code can be simplify by using built in functions like map and sum, for example this part
pair_sum = 0
for p in pairs:
pair_sum += int(p)
can become
pair_sum = sum( map(int,pairs) )
Uh oh, it looks like you're reusing the same variable i in the inner loop as the outer loop -- this is bad practice and can lead to bugs down the road.
What you're doing currently is adding both elements in each pair to sum and then printing that at the end, you can fix this in two different ways.
You can sum each pair, convert the sum to a string, and then concatenate that with your the rest of the sums as strings, or
You can print the sum of each pair immediately after summing them with print sum, which will print the number without the newline so that you can print all the results on a single line.
t = 8
string = "1 2 3 4 3 3 2 1"
string.replace(" ","")
string2 = [x for x in string]
print string2
for n in range(t-1):
string2.remove(' ')
print string2
def remover(ca):
newca = []
print len(ca)
if len(ca) == 1:
return ca
else:
for i in ca:
newca.append(int(i) - int(min(ca)))
for x in newca:
if x == 0:
newca.remove(0)
print newca
return remover(newca)
print (remover(string2))
It's supposed to be a program that takes in a list of numbers, and for every number in the list it subtracts from it, the min(list). It works fine for the first few iterations but not towards the end. I've added print statements here and there to help out.
EDIT:
t = 8
string = "1 2 3 4 3 3 2 1"
string = string.replace(" ","")
string2 = [x for x in string]
print len(string2)
def remover(ca):
newca = []
if len(ca) == 1: return()
else:
for i in ca:
newca.append(int(i) - int(min(ca)))
while 0 in newca:
newca.remove(0)
print len(newca)
return remover(newca)
print (remover(string2))
for x in newca:
if x == 0:
newca.remove(0)
Iterating over a list and removing things from it at the same time can lead to strange and unexpected behvaior. Try using a while loop instead.
while 0 in newca:
newca.remove(0)
Or a list comprehension:
newca = [item for item in newca if item != 0]
Or create yet another temporary list:
newnewca = []
for x in newca:
if x != 0:
newnewca.append(x)
print newnewca
return remover(newnewca)
(Not a real answer, JFYI:)
Your program can be waaay shorter if you decompose it into proper parts.
def aboveMin(items):
min_value = min(items) # only calculate it once
return differenceWith(min_value, items)
def differenceWith(min_value, items):
result = []
for value in items:
result.append(value - min_value)
return result
The above pattern can, as usual, be replaced with a comprehension:
def differenceWith(min_value, items):
return [value - min_value for value in items]
Try it:
>>> print aboveMin([1, 2, 3, 4, 5])
[0, 1, 2, 3, 4]
Note how no item is ever removed, and that data are generally not mutated at all. This approach helps reason about programs a lot; try it.
So IF I've understood the description of what you expect,
I believe the script below would result in something closer to your goal.
Logic:
split will return an array composed of each "number" provided to raw_input, while even if you used the output of replace, you'd end up with a very long number (you took out the spaces that separated each number from one another), and your actual split of string splits it in single digits number, which does not match your described intent
you should test that each input provided is an integer
as you already do a print in your function, no need for it to return anything
avoid adding zeros to your new array, just test first
string = raw_input()
array = string.split()
intarray = []
for x in array:
try:
intarray.append(int(x))
except:
pass
def remover(arrayofint):
newarray = []
minimum = min(arrayofint)
for i in array:
if i > minimum:
newarray.append(i - minimum)
if len(newarray) > 0:
print newarray
remover(newarray)
remover(intarray)
Here is my question
count += 1
num = 0
num = num + 1
obs = obs_%d%(count)
mag = mag_%d%(count)
while num < 4:
obsforsim = obs + mag
mylist.append(obsforsim)
for index in mylist:
print index
The above code gives the following results
obs1 = mag1
obs2 = mag2
obs3 = mag3
and so on.
obsforrbd = parentV = {0},format(index)
cmds.dynExpression(nPartilce1,s = obsforrbd,c = 1)
However when i run the code above it only gives me
parentV = obs3 = mag3
not the whole list,it only gives me the last element of the list why is that..??
Thanks.
I'm having difficulty interpreting your question, so I'm just going to base this on the question title.
Let's say you have a list of items (they could be anything, numbers, strings, characters, etc)
myList = [1,2,3,4,"abcd"]
If you do something like:
for i in myList:
print(i)
you will get:
1
2
3
4
"abcd"
If you want to convert this to a string:
myString = ' '.join(myList)
should have:
print(myString)
>"1 2 3 4 abcd"
Now for some explanation:
' ' is a string in python, and strings have certain methods associated with them (functions that can be applied to strings). In this instance, we're calling the .join() method. This method takes a list as an argument, and extracts each element of the list, converts it to a string representation and 'joins' it based on ' ' as a separator. If you wanted a comma separated list representation, just replace ' ' with ','.
I think your indentations wrong ... it should be
while num < 4:
obsforsim = obs + mag
mylist.append(obsforsim)
for index in mylist:
but Im not sure if thats your problem or not
the reason it did not work before is
while num < 4:
obsforsim = obs + mag
#does all loops before here
mylist.append(obsforsim) #appends only last
The usual pythonic way to spit out a list of numbered items would be either the range function:
results = []
for item in range(1, 4):
results.append("obs%i = mag_%i" % (item, item))
> ['obs1 = mag_1', 'obs2 = mag_2', 'ob3= mag_3']
and so on (note in this example you have to pass in the item variable twice to get it to register twice.
If that's to be formatted into something like an expression you could use
'\n'.join(results)
as in the other example to create a single string with the obs = mag pairs on their own lines.
Finally, you can do all that in one line with a list comprehension.
'\n'.join([ "obs%i = mag_%i" % (item, item) for item in range (1, 4)])
As other people have pointed out, while loops are dangerous - its easier to use range