手元の問題:
次のタプルのリスト(ID、国)があり、最終的にMySQLテーブルに格納します。
mylist = [(10, 'Other'), (10, 'India'), (10, 'Unknown'), (11, 'Other'), (11, 'Unknown'), (12, 'USA'), (12, 'UK'), (12, 'Other')]
次の条件を使用して、「その他」と「不明」を処理したい:
Value Replaced by => This value
----------------------------------------
Other & Unknown => Other
A country & Other => Country
A country & Unknown => Country
Python:
def refinelist(mylist):
'''Updating the list to remove unwanted values'''
'''
Other & Unknown => Other
A country & Other => Country
A country & Unknown => Country
'''
if 'Other' in mylist and 'Unknown' in mylist:
print 'remove unknown'
mylist.remove('Unknown')
if 'Other' in mylist and len(mylist) >= 2:
print 'remove other'
mylist.remove('Other')
if 'Unknown' in mylist and len(mylist) >= 2:
print 'remove unknown'
mylist.remove('Unknown')
return mylist
def main():
mylist = [(10, 'Other'), (10, 'India'), (10, 'Unknown'), (11, 'Other'), (11, 'Unknown'), (12, 'USA'), (12, 'UK'), (12, 'Other')]
d = {}
for x,y in mylist:
d.setdefault(x, []).append(y)
# Clean the list values
for each in d:
d[each] = refinelist(d[each])
## Convert dict to list of tuples for database entry
outlist = []
#result = [(key, value) for key,value in d.keys(), value in d.values()] ## Couldn't get this to work. Can the below loop be written as list comprehension with minimal footprint?
for key, value in d.items():
if len(value) == 1:
print key, value[0]
outlist.append((key, value[0]))
elif len(value) > 1:
for eachval in value:
print key, eachval
outlist.append((key, eachval))
print outlist
if __name__ == "__main__":
main()
出力:
remove unknown
remove other
remove unknown
remove other
10 India
11 Other
12 USA
12 UK
[(10, 'India'), (11, 'Other'), (12, 'USA'), (12, 'UK')]
質問 :
これはもっと効率的にできると思います。ディクトオーバーキルを使用していますか?
タプル(ルプル)のリストから始めて、それをdictに変換し、クリーンな操作を実行してから、ルプルに変換し直しますか?
MySQLテーブルに元のループを挿入してから、いくつかのクエリで「不明」と「その他」を処理することもできますが、タスクにはPythonを使用します。
pythonicソリューションまたはコードに関する批評家は大歓迎です。