我想知道向手动创建的 Python 列表中的每个元素添加单引号的最快方法。
手动生成列表时,我通常首先创建一个变量(例如 my_list),将其分配给列表括号,然后用单引号括起来的元素填充列表:
my_list = []
my_list = [ '1','baz','ctrl','4' ]
不过,我想知道是否有更快的方法来列出列表。问题是,我通常写完列表,然后进去给列表中的每个元素添加单引号。我认为这涉及太多的击键。
Jupyter NB 上的一个快速但无效的解决方案是突出显示列表元素并按键盘上的单引号。但是,如果您有一个想要转换为字符串的单词列表,则此方法不起作用;Python 认为您正在调用变量(例如 my_list = [1, baz, ctrl, 4 ])并抛出 NameError 消息。在此示例中,列表元素 baz 将抛出:
NameError: name 'baz' is not defined
我在 SO 上尝试了这个问题,但只有当您的列表已包含字符串时,它才有效:Join a list of strings in python 并将每个字符串用引号括起来。这个问题还假设您只使用数字:How to conversion list into string with quote in python。
我目前没有从事某个特定项目。这个问题只是出于教育目的。感谢大家的输入/快捷方式。
这是一个简单的回文检查器.该代码适用于数字,但不适用于字符串.
x = str(input("Enter a number: "))
if x == x[::-1]:
print x + " is a palindrome!"
else:
print x + " is not a palindrome!"
Run Code Online (Sandbox Code Playgroud)
当我尝试输入字符串时,我收到此错误:
File "palindrome.py", line 1, in <module>
x = str(input("Enter a number: "))
File "<string>", line 1, in <module>
NameError: name 'abba' is not defined
Run Code Online (Sandbox Code Playgroud) 我是 Python 新手,我正在尝试抓取 reddit 并将 UNIX 时间戳转换为日期。但是,当我运行此代码时,我收到名称错误。谁能告诉我为什么我会收到此错误?谢谢。
from datetime import datetime
def get_date(created):
return dt.datetime.fromtimestamp(created)
_timestamp = topics_data["created"].apply(get_date)
Run Code Online (Sandbox Code Playgroud) 在程序中输入 bond 时,出现名称错误未定义错误。
如果有人能够阐明我出错的地方,那就太好了。
elif greeting == "Bond":
house_value = int (input('''Please enter the value of the house: '''))
monthly_rate=float(input('''Enter the percentage of your interest rate ''')) / 100 /12
monthly_repay=int(input('''Please enter the number of months you plan to take to repay the bond'''))
x = (monthly_rate * house_value)/(1 - (1+monthly_rate)**(-monthly_repay))
print(f"The monthly repayment is {x:.2f}")
if y == 'Simple':
compound = investment* math.pow((1+rate),years)
print(f"The total amount of interest you will earn on your investment will be {compound:.2f} ")
Run Code Online (Sandbox Code Playgroud) 我目前正在研究python编程.
class A:
def LoadPosition(self):
FILE = open('a.txt', "r+")
i = 0
for node in self.nodes:
line = FILE.readline()
if i == 0:
scaling_factor == float(line)
i += 1
else:
tmpn, tmpx, tmpy, tmpa = line.split('\t')
node.id = tmpn
node.coordinate_x = float(tmpx)
node.coordinate_y = float(tmpy)
node.area = int(tmpa)
FILE.close()
Run Code Online (Sandbox Code Playgroud)
以前很好,但突然之间,它显示了NameError消息.请帮帮我.
提前致谢.
有谁知道我为什么会在这里收到"func undefined"错误?一切看起来都对我不对.
// dictutil.py
def func(L):
d = {}
for i in range(len(L)):
d[i] = L[i]
return d
Run Code Online (Sandbox Code Playgroud)
// Python命令行提示符:
import dictutil(尝试加载dictutil.py)
错误:
回溯(最近一次调用最后一次):NameError中的文件"",第1行:未定义名称'func'