手头的问题:
我有以下元组列表(ID,Country),我最终将存储在 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 是否矫枉过正?
我从一个元组(luples)列表开始,将其转换为字典,执行干净的操作,然后将其转换回 luples?
我可以在 MySQL 表中插入原始的 luples,然后用很少的查询处理“未知”和“其他”,但我更喜欢 Python 来完成这项任务。
非常感谢 Pythonic 解决方案或对代码的一些批评。