小编Art*_*zer的帖子

如何从单词列表到Python中的不同字母列表

使用Python,我试图将一个单词的句子转换成该句子中所有不同字母的平面列表.

这是我目前的代码:

words = 'She sells seashells by the seashore'

ltr = []

# Convert the string that is "words" to a list of its component words
word_list = [x.strip().lower() for x in words.split(' ')]

# Now convert the list of component words to a distinct list of
# all letters encountered.
for word in word_list:
    for c in word:
        if c not in ltr:
            ltr.append(c)

print ltr
Run Code Online (Sandbox Code Playgroud)

这段代码返回['s', 'h', 'e', 'l', 'a', 'b', 'y', 't', 'o', 'r'],这是正确的,但有更多的Pythonic方式来回答这个问题,可能是使用list …

python list-comprehension distinct filter letters

3
推荐指数
1
解决办法
480
查看次数

在允许Down数据库的同时关闭cx_Oracle连接

cx_Oracle数据库启动时,以下代码可以正常工作:

#!C:\Python27
import cx_Oracle

try:
    conn = cx_Oracle.connect("scott/tiger@oracle")

    try:
        curs = conn.cursor()
        curs.execute("SELECT dummy FROM sys.dual")
        print curs.fetchone()[0]
    finally:
        curs.close()
finally:
    conn.close()
Run Code Online (Sandbox Code Playgroud)

但是,如果在运行此脚本时数据库发生故障,NameError则会引发a:

Traceback (most recent call last):
  File "C:\Users\ArtMetzer\Documents\Code\Python\db_conn_test.py", line 14, in <module>
    conn.close()
NameError: name 'conn' is not defined
Run Code Online (Sandbox Code Playgroud)

这对我来说很有意义: cx_Oracle无法实例化连接,因此变量conn永远不会被设置,因此没有close()方法.

在Python中,什么是确保数据库连接关闭的最佳方法,同时仍然优雅地处理down数据库的条件?

做类似以下的事情对我来说似乎是一个巨大的障碍:

finally:
    try:
        conn.close()
    except NameError:
        pass
Run Code Online (Sandbox Code Playgroud)

python cx-oracle database-connection nameerror try-finally

3
推荐指数
2
解决办法
1万
查看次数