我目前正在python中执行if then else语句,但我有symbolUpper的30个条件:
if symbolUpper == "CAT":
growth = (((listOfRecords[2][5]-listOfRecords[2][4])/listOfRecords[2][4])*100)
peRatio = (listOfRecords[2][5]/listOfRecords[2][6])
print("Company: " + listOfRecords[2][0])
print("Industry: " + listOfRecords[2][3])
print("Exchange: " + listOfRecords[2][2])
print("Growth in 2013: {0:,.2f}%".format(growth))
print("Price/Earning ratio in 2013: {0:,.2f}".format(peRatio))
是否有更简单的方法在python中编码而不列出所有30个条件?我还包括了我的整个代码。
infile = open("Dow.txt", 'r')
listOfRecords = [line.rstrip() for line in infile]
infile.close()
for i in range(len(listOfRecords)):
listOfRecords[i]=listOfRecords[i].split(",")
listOfRecords[i][4] = eval(listOfRecords[i][4]) # price at the end of trading on 12/31/2012
listOfRecords[i][5] = eval(listOfRecords[i][5]) # price at the end of trading on 12/31/2013
listOfRecords[i][6] = eval(listOfRecords[i][6]) # 2013 earnings per share
print("Symbols for the Thirty DOW Stocks")
print(listOfRecords[0][1] + "\t" + listOfRecords[1][1] + "\t" +
listOfRecords[2][1] + "\t" + listOfRecords[3][1] + "\t" +
listOfRecords[4][1] + "\t" + listOfRecords[5][1] + "\t" +
listOfRecords[6][1] + "\t" + listOfRecords[7][1] + "\t" +
listOfRecords[8][1] + "\t" + listOfRecords[9][1] + "\n" +
listOfRecords[10][1] + "\t" + listOfRecords[11][1] + "\t" +
listOfRecords[12][1] + "\t" + listOfRecords[13][1] + "\t" +
listOfRecords[14][1] + "\t" + listOfRecords[15][1] + "\t" +
listOfRecords[16][1] + "\t" + listOfRecords[17][1] + "\t" +
listOfRecords[18][1] + "\t" + listOfRecords[19][1] + "\n" +
listOfRecords[20][1] + "\t" + listOfRecords[21][1] + "\t" +
listOfRecords[22][1] + "\t" + listOfRecords[23][1] + "\t" +
listOfRecords[24][1] + "\t" + listOfRecords[25][1] + "\t" +
listOfRecords[26][1] + "\t" + listOfRecords[27][1] + "\t" +
listOfRecords[28][1] + "\t" + listOfRecords[29][1] + "\t")
print()
symbol = input("Enter a symbol: ")
symbolUpper = symbol.upper()
if symbolUpper == "AXP":
growth = (((listOfRecords[0][5]-listOfRecords[0][4])/listOfRecords[0][4])*100)
peRatio = (listOfRecords[0][5]/listOfRecords[0][6])
print("Company: " + listOfRecords[0][0])
print("Industry: " + listOfRecords[0][3])
print("Exchange: " + listOfRecords[0][2])
print("Growth in 2013: {0:,.2f}%".format(growth))
print("Price/Earning ratio in 2013: {0:,.2f}".format(peRatio))
if symbolUpper == "BA":
growth = (((listOfRecords[1][5]-listOfRecords[1][4])/listOfRecords[1][4])*100)
peRatio = (listOfRecords[1][5]/listOfRecords[1][6])
print("Company: " + listOfRecords[1][0])
print("Industry: " + listOfRecords[1][3])
print("Exchange: " + listOfRecords[1][2])
print("Growth in 2013: {0:,.2f}%".format(growth))
print("Price/Earning ratio in 2013: {0:,.2f}".format(peRatio))
if symbolUpper == "CAT":
growth = (((listOfRecords[2][5]-listOfRecords[2][4])/listOfRecords[2][4])*100)
peRatio = (listOfRecords[2][5]/listOfRecords[2][6])
print("Company: " + listOfRecords[2][0])
print("Industry: " + listOfRecords[2][3])
print("Exchange: " + listOfRecords[2][2])
print("Growth in 2013: {0:,.2f}%".format(growth))
print("Price/Earning ratio in 2013: {0:,.2f}".format(peRatio))
if symbolUpper == "CSCO":
growth = (((listOfRecords[3][5]-listOfRecords[3][4])/listOfRecords[3][4])*100)
peRatio = (listOfRecords[3][5]/listOfRecords[3][6])
print("Company: " + listOfRecords[3][0])
print("Industry: " + listOfRecords[3][3])
print("Exchange: " + listOfRecords[3][2])
print("Growth in 2013: {0:,.2f}%".format(growth))
print("Price/Earning ratio in 2013: {0:,.2f}".format(peRatio))
答案 0 :(得分:1)
是。有。使用dict
:
lookup_dict = {'AXP': 0, 'BA': 1, ...}
try:
i = lookup_dict[symbolUpper]
growth = (((listOfRecords[i][5]-listOfRecords[i][4])/listOfRecords[i][4])*100)
peRatio = (listOfRecords[i][5]/listOfRecords[i][6])
print("Company: " + listOfRecords[i][0])
print("Industry: " + listOfRecords[i][3])
print("Exchange: " + listOfRecords[i][2])
print("Growth in 2013: {0:,.2f}%".format(growth))
print("Price/Earning ratio in 2013: {0:,.2f}".format(peRatio))
except KeyError:
... # symbolUpper not in dict
答案 1 :(得分:1)
当你有重复时,看看有什么相同,有什么不同。
将两者分开。
唯一不同的是索引。 有许多相同的部分。
如果您复制并粘贴了一次或两次以上,则需要重新考虑。正如他们所说,三次罢工,你重构。
您的代码也非常详细。例如,listOfRecords
会更好,只有records
。您还可以直接迭代数据,而不是迭代范围并索引到数据中:
print("Symbols for the Thirty DOW Stocks")
print('\t'.join(record[1] for record in records)
当您打开文件时,最好在之后关闭它。如果您使用with
语句,Python将自动为您执行此操作。此外,默认情况下模式为r
,因此您无需指定它:
with open("Dow.txt") as infile:
records = [line.rstrip() for line in infile]
# file will be closed here
你不应该使用eval
。例如,如果输入包含删除所有文件的命令,则可能会造成严重破坏。如果您只有字面数字,则可以安全地使用literal_eval
:
from ast import literal_eval
records = [records.split(',') for record in records]
for record in records:
record[4] = literal_eval(record[4]) # price at the end of trading on 12/31/2012
record[5] = literal_eval(record[5]) # price at the end of trading on 12/31/2013
record[6] = literal_eval(record[6]) # 2013 earnings per share
解决重复和索引的问题。记录包含库存的符号,因此您可以使用记录构建查找表。在Python中,查找表最好用dict
表示:
lookup = {record[1]: record
for record in records}
旁白:现在我们有一个基于DOW符号的查找表,我们可以在打印符号时使用它,因为迭代字典会给你键(这是DOW符号):
print("Symbols for the Thirty DOW Stocks")
print('\t'.join(symbol for symbol in records)
您可以使用以下函数替换其余代码:
def report(dow):
growth = 100 * (dow[5] - dow[4]) / dow[4]
peRatio = dow[5] / dow[6]
print("Company: " + dow[0])
print("Industry: " + dow[3])
print("Exchange: " + dow[2])
print("Growth in 2013: {0:,.2f}%".format(growth))
print("Price/Earning ratio in 2013: {0:,.2f}".format(peRatio))
您可以将其称为:
report(lookup[symbol])
进一步的改进包括使用csv
模块,当您手动执行split(',')
时,它可以为您执行此操作。此外,它正确处理引用字段,因此如果您的公司名称中包含任何逗号,例如Google,Inc,如果它被引用为“Google,Inc”csv
将会处理它而不会在逗号上拆分:
import csv
with open("Dow.txt") as infile:
records = list(csv.reader(infile))
此外,namedtuple
可与csv
条记录完美配合。
Dow = namedtuple('Dow', 'company symbol exchange industry previous price earning')
records = [Dow(*[literal_eval(value) for value in record])
for record in records]
然后您的计算可以更容易阅读:
growth = 100 * (dow.price - dow.previous) / dow.previous
pe_ratio = dow.price / dow.earning
最后,您的报告应与print
分开,因为您可能希望在其他地方使用它,例如记录,写入文件等。使用格式字段也使其更具可读性。
report_format = ('Company: {dow.company}\n'
'Industry: {dow.industry}\n'
'Exchange: {dow.exchange}\n'
'Growth in 2013: {growth:,.2f}%\n'
'Price/Earning ratio in 2013@ {pe_ratio:,.2f}\n')
report = report_format.format(dow=record,
growth=growth,
pe_ratio=pe_ratio)
print(report)
答案 2 :(得分:0)
将所有要比较的字符串保存在列表中,然后获取所需字符串的索引并使用该索引执行任务。
symbolUpperList = ["AXP", "BA", "CAT", ...]
i = symbolUpperList.index(symbolUpper)
growth = (((listOfRecords[i][5]-listOfRecords[i][4])/listOfRecords[i][4])*100)
peRatio = (listOfRecords[i][5]/listOfRecords[i][6])
print("Company: " + listOfRecords[i][0])
print("Industry: " + listOfRecords[i][3])
print("Exchange: " + listOfRecords[i][2])
print("Growth in 2013: {0:,.2f}%".format(growth))
print("Price/Earning ratio in 2013: {0:,.2f}".format(peRatio))
答案 3 :(得分:0)
代码如下:
infile = open("Dow.txt", 'r')
listOfRecords = [line.rstrip() for line in infile]
symbolUpper_db = {"AXP": 1, "BA" : 2, "CAT":3, "CSCO":4 }
def compute( symbol_idx ):
growth = (((listOfRecords[symbol_idx][5]-listOfRecords[symbol_idx][4])/listOfRecords[symbol_idx][4])*100)
peRatio = (listOfRecords[symbol_idx][5]/listOfRecords[symbol_idx][6])
print("Company: " + listOfRecords[symbol_idx][0])
print("Industry: " + listOfRecords[symbol_idx][3])
print("Exchange: " + listOfRecords[symbol_idx][2])
print("Growth in 2013: {0:,.2f}%".format(growth))
print("Price/Earning ratio in 2013: {0:,.2f}".format(peRatio))
compute(symbolUpper_db[symbolUpper])
答案 4 :(得分:0)
您的 passport.use(
new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(request, email, password, done) {
process.nextTick(function() {
User.findOne({ username }, function(err, user) {
if (err) {
return done(err);
} else if (!users.length) {
return done(null, false, { errorUsername: "user doesnt exist" });
} else {
var user = users[0];
bcrypt.compare(password, user.password, function(err,
res) {
if (res) {
return done(null, user);
} else {
return done(null, false);
}
});
}
}
});
}
});
});
})
);
只有更改。所以为每个index
这是简单的if条件,
symbolUpper
symbolUpper ==" AXP"否则错误
i = 2 if symbolUpper == "CAT" else 1 if symbolUpper == "BA" else 0 if
或者您可以尝试使用词典查找,
if i:
growth = (((listOfRecords[i][5]-listOfRecords[i][4])/listOfRecords[i][4])*100)
peRatio = (listOfRecords[i][5]/listOfRecords[i][6])
print("Company: " + listOfRecords[i][0])
print("Industry: " + listOfRecords[i][3])
print("Exchange: " + listOfRecords[i][2])
print("Growth in 2013: {0:,.2f}%".format(growth))
print("Price/Earning ratio in 2013: {0:,.2f}".format(peRatio))