我有一个字典列表,我想根据某些条件提取某些数据.如果货币显示美元且大于0,我想只提取货币(如int/float).
curr = [{'currency': '6000.0000,EUR', 'name': 'Bob'},
{'currency': '0.0000,USD', 'name': 'Sara'},
{'currency': '2500.0000,USD', 'name': 'Kenny'},
{'currency': '0.0000,CND', 'name': 'Debbie'},
{'currency': '2800.0000,USD', 'name': 'Michael'},
{'currency': '1800.0000,CND', 'name': 'Aaron'},
{'currency': '2500.0000,EUR', 'name': 'Peter'}]
Run Code Online (Sandbox Code Playgroud)
结果:
usd_curr = [2500.0000, 2800.0000]
Run Code Online (Sandbox Code Playgroud)
这就是我所做的.
usd_curr = [line for line in data if ',USD' in line['currency']]
usd_curr = [float(elem['currency'].split(',')[0]) for elem in curr if float(elem['currency'].split(',')[0]) > 0]
Run Code Online (Sandbox Code Playgroud)
列表有效,但我的问题是这个 - 有更好的方法在列表推导中使用变量,所以它看起来像这样:
usd_curr = [var = float(elem['currency'].split(',')[0]) for elem in curr if var > 0]
Run Code Online (Sandbox Code Playgroud) 我需要处理一个需要NLTK的项目,所以我在两周前开始学习Python,但很难理解Python和NLTK.
从NLTK文档中,我可以理解以下代码,如果我在下面的代码中手动添加单词apple和pear,它们的效果很好.
from nltk.corpus import wordnet as wn
apple = wn.synset('apple.n.01')
pear = wn.synset('pear.n.01')
print apple.lch_similarity(pear)
Output: 2.53897387106
Run Code Online (Sandbox Code Playgroud)
但是,我需要使用NLTK来处理项目列表.例如,我有一个下面的项目列表,我想比较list1中的项目和list2 - 例如:将list1中的word1与list2中的每个单词进行比较,然后将list1中的word2与list2中的每个单词进行比较,直到所有单词为止list1进行了比较.
list1 = ["apple", "honey", "drinks", "flowers", "paper"]
list2 = ["pear", "shell", "movie", "fire", "tree", "candle"]
wordFromList1 = list1[0]
wordFromList2 = list2[0]
wordFromList1 = wn.synset(wordFromList1)
wordFromList2 = wn.synset(wordFromList2)
print wordFromList1.lch_similarity(wordFromList2)
Run Code Online (Sandbox Code Playgroud)
上面的代码当然会出错.任何人都可以告诉我如何将变量传递给synset方法[wn.synset(*pass_variable_in_here*)],以便我可以使用双循环来获取它们的lch_similarity值.谢谢.
我正在尝试实现和算法,我不知道如何在Python中实现.
算法给出为 [e ^ -ax] * [((e ^ by) - (e ^ -ax)) / ((e ^ by) + (e ^ -ax))]
哪里:
^ 代表的力量e 是欧拉的数字,其值为 2.718a并且b是常数并且作为a = 0.2和给出b = 0.45x和y是变量,其中a和b将永远是>= 0这是我想出的,但我不确定这是否正确.如果有人能告诉我它是否正确或是否有更简单的方法来实现这一点会很好,因为它现在看起来非常复杂.
valueA = 0.2 * x
valueB = 0.45 * y
results = math.pow(math.e, -valueA) * (math.pow(math.e, valueB) - math.pow(math.e, -valueB)) / (math.pow(math.e, valueA) + math.pow(math.e, -valueB))
Run Code Online (Sandbox Code Playgroud) 我是新来的Centos 6和Linux.
我需要安装,Python 3.4但Centos 6默认情况下Python 2.6.6.
我安装Python 3.4到了/usr/local/lib/Python3.4.
但是,我在安装时遇到问题mysqlclient.
我试过了pip3.4 install mysqlclient.
这是错误消息.
错误
_mysql.c:29:23: error: my_config.h: No such file or directory
_mysql.c:30:19: error: mysql.h: No such file or directory
_mysql.c:31:26: error: mysqld_error.h: No such file or directory
_mysql.c:51:20: error: errmsg.h: No such file or directory
_mysql.c:74: error: expected specifier-qualifier-list before ‘MYSQL
_mysql.c:88: error: expected specifier-qualifier-list before ‘MYSQL_RES’
_mysql.c: In function ‘_mysql_Exception’: …Run Code Online (Sandbox Code Playgroud) 我需要存储2个彼此连接的值数组.数组由一组字符串和一组整数/双精度值组成.数据的大小不固定.
一个例子:
Data 1: AA, 13
Data 2: BB, 6
Data 3: GG, 2
Run Code Online (Sandbox Code Playgroud)
我试着看看2D阵列.有没有更好的方法来存储价值观?我可能需要多维数组来存储值.任何人都可以指出我正确的方向或给我一个方法来创建2D数组以及如何添加/检索元素?
我有一个带有未指定编号的int列表.我想找到列表中与某个值匹配的两个整数之间的区别.
#Example of a list
intList = [3, 6, 2, 7, 1]
#This is what I have done so far
diffList = []
i = 0
while (i < len(intList)):
x = intList[i]
j = i +1
while (j < len(intList)):
y = intList[j]
diff = abs(x-y)
diffList.append(diff)
j += 1
i +=1
#Find all pairs that has a difference of 2
diff = diffList.count(2)
print diff
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?
编辑:对代码进行了更改.这就是我想要做的.我想知道的是除了循环之外我还能使用什么.
我正在尝试创建一个包含所有数据库操作的类。我想每当调用这个类时就启动一个 MySQL 连接,执行它需要执行的任何数据库操作,并在完成后关闭它。
这是我到目前为止所拥有的:
import MySQLdb
class Database_Test(object):
def __init__(self, db_local):
self.db_conn = MySQLdb.connect(**db_local)
self.db_cursor = self.db_conn.cursor()
def get_row(self, sql, data = None):
self.db_cursor.execute(sql)
self.resultset = self.db_cursor.fetchall()
self.db_cursor.close()
return self.resultset
# Close db connection something like this?
# db_conn.close()
db_config = {
'host':"127.0.0.1", # database host
'port': 3306, # port
'user':"root", # username
'passwd':"admin", # password
'db':"test", # database
'charset':'utf8' # charset encoding
}
sql = "SELECT * FROM mytest LIMIT 10"
test = Database_Test(db_config)
test.get_row(sql)
print(test)
Run Code Online (Sandbox Code Playgroud)
这就是我得到的:
<__main__.Database_Test object …Run Code Online (Sandbox Code Playgroud) 使用柯林斯头规则处理项目以获得一个句子的标题.
这是我得到的错误:
File "C:\Users\PC\Desktop\Python27\PyProject\src\Feature\FeatureExtractor.py", line 225, in collinsHeadExtractor
if raw['whWord']=='whWord-what':
TypeError: 'NoneType' object has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud)
这是生成错误的代码的一部分:
def whoPattern(question):
p1 = re.compile("^[w|W]ho (is|are|was|were)( the)*( \`\`)*( [A-Z][a-z]+)+( \'\')* \?$")
if p1.match(question):
return "HUM:desc"
p2 = re.compile("^[w|W]ho (is|was) .*")
if p2.match(question):
return "Hum:ind"
if training:
file = DBStore.trainingRoot+"\\headword_question"+colName+".txt"
else:
file = DBStore.testingRoot+"\\headword_question"+colName+".txt"
f = open(file,'r')
p = re.compile(r"(?P<head>.+)::(?P<question>.+)")
i = 0
rawQuestions = DBStore.getDB()['raw'+colName]
p2 = re.compile('\.')
headWord = []
for line in f:
print iWor
i = i + 1 …Run Code Online (Sandbox Code Playgroud) 我有一个列表,其中包含列表中的列表.内部列表包含两个项目,inner_list [0]是标识符/键,inner_list [1]是对应的值.我想将它们放入一个字典中,其中共享相同键的值将附加到同一个键.
一个例子:
list = [['Jan', 'Jim'], ['Feb', 'Maggie'], ['Jan', 'Chris'], ['Sept', 'Joey'],..['key', 'value']]
Run Code Online (Sandbox Code Playgroud)
我正在寻找的结果:
Jan = ['Jim', 'Chris']
Feb = ['Maggie']
Sept = ['Joey']
Run Code Online (Sandbox Code Playgroud)
我能用Python优雅地做到这一点吗?
我已经将从mySQL查询的一些元素(水果名称)插入到数组中.现在,我想从数组中删除某些项目.如果数组存在,我想删除'Apple'和'Orange'.这是我尝试但我收到错误消息.
Array Example:
Array ( [1] => Orange [2] => Apple)
foreach($terms as $k => $v)
{
if (key($v) == "Apple")
{
unset($terms[$k]);
}
elseif( key($v) == "Orange")
{
unset($terms[$k]);
}
}
>>> Warning: key() expects parameter 1 to be array, string given //same error repeated 4 times
Run Code Online (Sandbox Code Playgroud)
我在这里提到了这个链接:如何在foreach循环中删除数组元素? 如果有人能指出我做错了什么,我将不胜感激.
当我尝试调用Laravel的Mail:send方法时出现此错误。
{"errors":[{"message":"Internal Server Error",
"debug":{"code":1,"message":"Class 'MyMail\\Mail' not found",..
Run Code Online (Sandbox Code Playgroud)
app / config / mail.php中的所有设置已经过验证。
namespace MyMail;
class GetMyMail extends Controller
{
public function __construct()
{
parent::__construct();
}
public function sendMail()
{
//$json_data is data stored in json
$users = json_decode($json_data, true);
foreach($users as $user)
{
Mail::send('template1', $user, function($message) use ($user)
{
$message->to($user['email'], $user['first_name'])
->subject('Laravel Email Test');
});
}
}
}
Run Code Online (Sandbox Code Playgroud) 我试图将数据框中的所有值增加 1,除了 ID 列之外。
例子:
结果:
这是我到目前为止所拥有的,但是当我有很多列要做时(例如 50),它会变得有点长。
df_add = df.select(
'Id',
(df['col_a'] + 1).alias('col_a'),
..
..
)
Run Code Online (Sandbox Code Playgroud)
有没有更Pythonic的方法来达到相同的结果?