让我假装我有以下代码.
num1 = 33
num2 = 45
num3 = 76
lst = ['one', 'two', 'three']
for item in lst:
if item == 'one':
print num1
elif item == 'two':
print num2
elif item == 'three':
print num3
Run Code Online (Sandbox Code Playgroud)
当列表和打印句子之间没有相关性时,有没有办法使这更优雅?意思是,有没有办法摆脱ifs和elifs?
我试图从if语句中的另一个文件返回(执行)一个函数.我已经读过返回语句不起作用,我希望有人知道什么语句可以让我调用外部函数.
该函数创建一个沙箱,但如果存在,我想传递if语句.
这是我使用的一小段代码.
import mks_function
from mksfunction import mks_create_sandbox
import sys, os, time
import os.path
if not os.path.exists('home/build/test/new_sandbox/project.pj'):
return mks_create_sandbox()
else:
print pass
Run Code Online (Sandbox Code Playgroud) 接下来是我的代码,它可以打印'xxx'
,但最后运行错误:
def a(object):
print 'xxx'
@a
def b():
return 'bbb'
b()
Run Code Online (Sandbox Code Playgroud)
在你的答案中,请尝试使用代码示例而不是文本,因为我的英语不是很好.谢谢.
我总是要知道为什么,而不仅仅是如何,所以我走了:
这是如何运作的:
'{0:01.2f}'.format(5.555) #returns '5.55'
'{0:01.1f}'.format(5.555) #returns '5.5'
'{0:1.2f}'.format(5.555) #returns '5.55' again
'{0:1.1f}'.format(5.555) #returns '5.5' again
Run Code Online (Sandbox Code Playgroud)
当我有额外的零时,为什么这不会通过返回'05 .5'而不仅仅是'5.5'来添加零填充.它似乎没有用.
另外,为什么字符串0:1.1f而不是0:0.1f等.它只是一个约定使用十进制之前的数字而不是零,或者是语法?
我有一个wxPython核对表框,它返回一个整数列表.我想使用整数来查找字典中的项目.我不确定最好的方法.有什么建议?
我试图将列表中的几个值放入一个字符串中.我的代码如下:
ID = [0, 1, 2]
print 'ID {0}, {1}, and {2}.'.format(ID)
Run Code Online (Sandbox Code Playgroud)
要么
print (r'(ID\s*=\s*)(\S+)').format(ID)
Run Code Online (Sandbox Code Playgroud)
这不起作用.有谁知道我哪里出错了.第二行中的代码打印出列表:
[0, 1, 2]
Run Code Online (Sandbox Code Playgroud)
第一行说:
File "tset.py", line 39, in b
print 'ID {0}, {1}, and {2}.'.format(ID)
IndexError: tuple index out of range
Run Code Online (Sandbox Code Playgroud)
谢谢
我有这样的代码:
try:
var = request.POST['var']
except NameError:
var = ''
Run Code Online (Sandbox Code Playgroud)
为什么总是在"except"执行后编码?即使request.POST['var']
存在.
我想对数组 c 进行排序。但我没有得到答案 a、b、c、d。相反,我得到了 a、b、d、c。我能做什么,对整个数组进行排序,而不仅仅是一行?
编辑:我想对数字进行排序。并且连接的字母应该与排序的数字具有相同的顺序。对不起,我的问题不清楚。也许我应该先加入数字和字母。像这样:[['a',1]['b',2]....
a = ['a','b','d','c']
b = [1,2,4,3]
c = [[],[]]
c[0]=a
c[1]=b
c[1].sort()
print(c)
Run Code Online (Sandbox Code Playgroud) 我有一个课程如下:
class X:
def __init__(self):
self.sum_x =0.0
self.sum_x_squared=0.0
self.var_x =0.0
self.sum_y =0.0
self.sum_y_squared=0.0
self.var_y =0.0
def update(self,data):
[x,y,vx,vy]=data
self.update_sums(self.sum_x,self.sum_x_squared,x)
self.update_sums(self.sum_y,self.sum_y_squared,y)
.
def update_sums(self,sums,squares,val):
sums += val
squares += val*val
.
Run Code Online (Sandbox Code Playgroud)
我想通过成员变量sum_x
,sum_x_squared
等等的update_sums
功能更新我怎么做到这一点,我很困惑.
谢谢
我有以下列表:
mylist = ['Hello,\r', 'Whats going on.\r', 'some text']
Run Code Online (Sandbox Code Playgroud)
当我将"mylist"写入名为file.txt的文件时
open('file.txt', 'w').writelines(mylist)
Run Code Online (Sandbox Code Playgroud)
由于\ r \n,我得到每行一点文字
Hello,
Whats going on.
some text
Run Code Online (Sandbox Code Playgroud)
如何操纵mylist来替换\r
空格?最后我需要这个file.txt
:
Hello, Whats going on. sometext
Run Code Online (Sandbox Code Playgroud)
它必须是一个列表.
谢谢!