私信  •  关注

MrGeek

MrGeek 最近创建的主题
MrGeek 最近回复了
6 年前
回复了 MrGeek 创建的主题 » python中如何在负数前加括号

可以更好地利用Python的字符串格式,使用映射整数的函数 n str(n) 如果是肯定的,或者 (-str(n)) 如果是阴性的:

def f(n):
    return str(n) if n >= 0 else '(%d)' % n

print("The quadratic equation is : {0}x2+{1}x+{2}".format(f(a), f(b), f(c)))

我建议一种更好的格式是实际放置数字的符号,而不是静态的 + 在操作数之间,并避免使用括号:

def f(n):
    return ('+' if n >= 0 else '-') + '%d' % abs(n)

eq_f = '{0}x2{1}x{2}'

print("The quadratic equation is : " + eq_f.format(f(a), f(b), f(c)))

输出(示例):

Enter the value of a:-1
Enter the value of b:5
Enter the value of c:-4
The quadratic equation is : -1x2+5x-4
6 年前
回复了 MrGeek 创建的主题 » 我需要帮助用python处理json格式的数据

只需循环浏览列表中的对象并为每个对象打印所需的字符串:

arr = [{"word":"ingenious","score":1828,"numSyllables":3}, 
{"word":"heterogeneous","score":1139,"numSyllables":5}]

for obj in arr:
    print('{} ({})'.format(obj['word'], obj['numSyllables']))

输出:

ingenious (3)
heterogeneous (5)

如果需要,也可以在一行中执行此操作:

print('\n'.join('{} ({})'.format(obj['word'], obj['numSyllables']) for obj in arr))

输出:

巧妙(3)
异构(5)

更快一点( based on this post )使用列表乘法要短得多:

>>> [1] * 9
[1, 1, 1, 1, 1, 1, 1, 1, 1]
6 年前
回复了 MrGeek 创建的主题 » python-从ip地址中删除前导零

您可以删除前面带有 . ^ (线的起点)后面跟着除 . 在它之前( . 或开始行):

import re

def remove_zeros_from_ip(ip_add):
  return re.sub('(^|\.)0+(?=[^.])', r'\1', ip_add)

测试:

ip = '10.0.01.10'
print(remove_zeros_from_ip(ip))

ip1 = '10.00.002.20'
print(remove_zeros_from_ip(ip1))

ip2 = '0010.00.02.0020'
print(remove_zeros_from_ip(ip2))

输出:

10.0.1.10
10.0.2.20
10.0.2.20

非正则表达式解决方案是将字符串拆分为 . 使用 str.rstrip 若要删除前导零,请使用 str.join 要重建字符串:

def remove_zeros_from_ip(ip_add): 
  return '.'.join(p.lstrip('0') or '0' for p in ip_add.split('.'))
6 年前
回复了 MrGeek 创建的主题 » 使用python字典作为查找表输出新值

您不需要循环来执行此操作,只需使用 df.map :

...
>>> df['newletter'] = df['letter'].map(lkup)
>>> print(df)
  letter newletter
0      a         b
1      a         b
2      c         d
3      d         e
4      d         e
6 年前
回复了 MrGeek 创建的主题 » python.sort()不能完全排序数字[重复]

你在排序字符串,而不是数字,你的 getVolume 需要将值转换为 float 第一:

def getVolume(e):
    return float(e["priceChangePercent"])

或者,您可以在 key 如果希望字符串由 获取音量 :

tickers.sort(reverse = True, key = lambda x : float(getVolume(x)))
6 年前
回复了 MrGeek 创建的主题 » 为什么我的列表没有被python覆盖?[副本]

要覆盖,请使用索引:

List = ["I?", "Can", "!Not", "Do.", "It"]
l=[]
BadChars = ["?", "!", "."]
for i in range(len(List)):
    for j in BadChars:
        if j in List[i]:
            List[i] = List[i].strip(j)
    l.append(List[i])
print(l)
print(List)