Revenue = [400000000,10000000,10000000000,10000000]
s1 = []
for x in Revenue:
message = (','.join(['{:,.0f}'.format(x)]).split())
s1.append(message)
print(s1)
The output I am getting is something like this [['400,000,000'], ['10,000,000'], ['10,000,000,000'], ['10,000,000']] and I want it should be like this -> [400,000,000, 10,000,000, 10,000,000,000, 10,000,000]
Can someone please help me on this, I am new to python
If your goal is to just add in the commas you will be stuck with the ' ' due to the fact its going to be a str but you can eliminate that nesting by using a simpler list comprehension
Revenue = [400000000,10000000,10000000000,10000000]
l = ['{:,}'.format(i) for i in Revenue]
# ['400,000,000', '10,000,000', '10,000,000,000', '10,000,000']
You could also unpack the list into variables and then print each variable without quotes
v, w, x, y = l
print(v)
# 400,000,000
You can print the unpacked list but that will just be output
print(*l)
# 400,000,000 10,000,000 10,000,000,000 10,000,000
Expanded Loop:
l = []
for i in Revenue:
l.append('{:,}'.format(i))
I'm not sure why you want the output you've shown, because it is hard to read, but here is how to make it:
>>> Revenue = [400000000,10000000,10000000000,10000000]
>>> def revenue_formatted(rev):
... return "[" + ", ".join("{:,d}".format(n) for n in rev) + "]"
...
>>> print(revenue_formatted(Revenue))
[400,000,000, 10,000,000, 10,000,000,000, 10,000,000]
Related
The .txt file has a string like this:
[[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]9.5
My goal is to separate that final number from the list and then turn each of them into a list of lists and a float respectively. I've managed to seperate them but they are still strings and I can't convert them...
Here's the code I have:
def string_to_list(file):
for i in os.listdir(path):
if i == file:
openfile = open(path5+'/'+ i, 'r')
values = openfile.read()
p = ']]'
print(values)
print()
bef, sep, after= values.partition(p)
string1 = values.replace(after,'')
print(string1)
print()
print(after)
The output is, using the previous exemple:
[[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]9.5
[[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]
9.5
But they are all strings yet.
How can I make this work?
Thank you
ast.literal_eval can do this. json.loads could, as well.
import ast
s = "[[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]9.5"
i = s.rfind(']')
l = ast.literal_eval(s[:i+1])
o = float(s[i+1:])
print(l, o)
Here is a simple way that only uses list append and loops:
x = list(a[1:len(a)-1]) # remove the outisde brackets
res = []
tmp = []
for e in x:
if e == ']':
res.append(tmp)
tmp = []
continue
if e not in ('[', ',', ' ', ''):
tmp.append(int(e))
You can also use the eval() function after getting the string1 and after values in your code.
myList = eval(string1) #type(myList) will give you list
myFloat = eval(after) #type(myFloat) will give you float
I am trying to solve through a challenge where I have to reorder the letters in string s in the order it appears on string t. For example:
For s = "weather" and t = "therapyw", the output should be
sortByString(s, t) = "theeraw";
For s = "good" and t = "odg", the output should be
sortByString(s, t) = "oodg".
This is my code:
def sortByString(s, t):
s_list = list(s)
t_list = list(t)
output = []
for i in range(len(t_list)):
if t_list[i] in s_list:
output.insert(i, t_list[i])
return ''.join(output)
It works for all cases except if the same letter exists more than once.
s: "weather"
t: "therapyw"
Output:
"theraw"
Expected Output:
"theeraw"
How can I handle this situation in my code above? What am I missing? I appreciate all help but instead of just blurting out the answer, I would like to know what I'm doing wrong.
The issue with your current code is that it only adds one copy of each character in t to output, regardless of how many times it occurs in s. You can work around that by looping over the count of that character in s and appending to output for each count:
def sortByString(s, t):
s_list = list(s)
t_list = list(t)
output = []
for i in range(len(t_list)):
for _ in range(s_list.count(t_list[i])):
output.append(t_list[i])
return ''.join(output)
print(sortByString('weather',"therapyw"))
print(sortByString('good',"odg"))
Output:
theeraw
oodg
You can simplify the loop by just adding copies of a list with the current character according to the count of the character in s:
for c in t_list:
output = output + [c] * s_list.count(c)
Easy way
Use enumerate and turn your string into a dict
def sortByString(s, t):
s_list = list(s)
t_list = list(t)
orderdict = {char: index for index, char in enumerate(t_list)}
output = sorted(list('weather'),key=orderdict.get)
return ''.join(output)
This will allow repeated values
Example
>>> sortByString('weather',"therapyw")
'theeraw'
Modification to OP's code
Just add the element number of times it appear in s to the output
def sortByString(s,t):
s_list = list(s)
t_list = list(t)
output = []
for i in range(len(t_list)):
if t_list[i] in s_list:
output.append(t_list[i]*s_list.count(t_list[i]))
return ''.join(output)
output
>>> sortByString('weather',"therapyw")
'theeraw'
2 steps:
a. create a sorted list of characters in s and their order in t using index()
b. use zip(* to extract the sorted list of characters
s = "weather"
t = "therapy"
a = sorted([(t.index(c),c) for c in s])
b = ''.join(list(zip(*a))[1])
print(b)
Output:
theeraw
I want to create a random list of names from a from a bigger list of names. The problem is, there is no space between the names that are generated. I cannot understand how to put space. Here's my code
import random
final_list = ""
a=0
sss = ("John","Adam","Sara","Lory","Dick","Popeye")
while a<7:
x = random.choice(sss)
final_list += x
a += 1
print (final_list)
The result is something like this:
SaraAdamDickPopeyeSaraPopeyeLory
How can I add space between the names? Also, can anyone suggest a shorter way to do this code?
You can add an additional empty empty string at the original concatenation:
x = random.choice(sss)
final_list += " "+x if final_list else x
a += 1
Or, more precisely, use ' '.join in list comprehension:
sss = ("John","Adam","Sara","Lory","Dick","Popeye")
final_string = ' '.join(random.choice(sss) for i in range(7))
To avoid leading or trailing spaces, check if length of final_list is already greater than zero.
import random
final_list = ""
a=0
sss = ("John","Adam","Sara","Lory","Dick","Popeye")
while a<7:
x = random.choice(sss)
final_list = final_list + " " + x if len(final_list) > 0 else x
a += 1
print (final_list)
If you don't want explicit checking, you can make use of strip function to remove leading and trailing spaces after you construct the final_list.
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
i've been reading from the file and i have hard time getting rid of "\t"
i've tried using i.strip().split("\t")[1] and append it to the list. but if theres more tabs in a row it isnt very useful
for example:
if i do what i described i get
z=['\t\t\t\twoman-in-lingerie', 'newspaper-photo', 'reference-to-marie-antoinette', '\tempty-grave', '\t\t\tbased-on-play', '\t\t\tcanadian-humor', '\t\t\tsitcom', 'hypocrisy', 'stripper']
now i dont know how to remove those tabs, ive been trying to get trough the list and change each element on its own bit it was unsuccessful
If you're just trying to remove tabs you can use this list comprehension:
l2 = [item.strip('\t') for item in l1]
That'll get rid of any leading or trailing tabs on each element.
If you don't want any of the tabs you can use filter after reading everything:
for item in my_list:
item = item.filter(lambda x: x != '\t', item)
The best you can do is use the replace function, replacing tabs ('\t') for empty strings (''):
>>> z = ['\t\t\t\twoman-in-lingerie', '\t\t\tsitcom']
>>> map(lambda x: x.replace('\t',''), z)
['woman-in-lingerie', 'sitcom']
This might give you an idea:
>>> import re
>>> re.sub('\t+','\t', 'hello\t\t\t')
'hello\t'
>>>
z = '''\t\t\t\twoman-in-lingerie
newspaper-photo\t\t\t\t reference-to-marie-antoinette
\tempty-grave
\t\t\tbased-on-play
\t\t\tcanadian-humor\t\t\t
\t\t\tsitcom
hypocrisy\t\t\t\t\tstripper'''
import re
def displ(x):
return '\n'.join(map(repr,x.splitlines(True)))
print displ(z)
print '-------------------------------'
zt = re.sub('\t+',' ',z)
print displ(zt)
print '-------------------------------'
zt = re.sub('(^\t+)|(\t+)',
lambda mat: '' if mat.group(1) else ' ',
z,
flags = re.MULTILINE)
print displ(zt)
print '-------------------------------'
zt = re.sub('(^[ \t]+)|([ \t]+)',
lambda mat: '' if mat.group(1) else ' ',
z,
flags = re.MULTILINE)
print displ(zt)
result
'\t\t\t\twoman-in-lingerie\n'
'newspaper-photo\t\t\t\t reference-to-marie-antoinette\n'
'\tempty-grave\n'
'\t\t\tbased-on-play\n'
'\t\t\tcanadian-humor\t\t\t\n'
'\t\t\tsitcom\n'
'hypocrisy\t\t\t\t\tstripper'
-------------------------------
' woman-in-lingerie\n'
'newspaper-photo reference-to-marie-antoinette\n'
' empty-grave\n'
' based-on-play\n'
' canadian-humor \n'
' sitcom\n'
'hypocrisy stripper'
-------------------------------
'woman-in-lingerie\n'
'newspaper-photo reference-to-marie-antoinette\n'
'empty-grave\n'
'based-on-play\n'
'canadian-humor \n'
'sitcom\n'
'hypocrisy stripper'
-------------------------------
'woman-in-lingerie\n'
'newspaper-photo reference-to-marie-antoinette\n'
'empty-grave\n'
'based-on-play\n'
'canadian-humor \n'
'sitcom\n'
'hypocrisy stripper'
I use the function displ() to display in a manner that shows the escaped characters