如果有两个格式不一样的 list, 怎么样判断是否含有“相同的单词”呢?

2015-01-15 07:34:16 +08:00
 meteor2013
第一个: [['Vodka'], ['Whisky'], ['Scotch'], ['Brandy']]
第二个: (['Vodka', 'today', 'nice', 'drink', 'Scotch'], 'Group 2')
2779 次点击
所在节点    Python
11 条回复
aheadlead
2015-01-15 07:44:43 +08:00
列表解析为set...交给set处理吧...
icedx
2015-01-15 07:46:52 +08:00
for I in l1:
~for j in l2:
Fox4y
2015-01-15 08:29:44 +08:00
a=[['Vodka'], ['Whisky'], ['Scotch'], ['Brandy']]
>>> for line in a:
... "Vodka" in line
ztcontrol
2015-01-15 09:09:36 +08:00
外行, 写的不对请指正
l1 = [['Vodka'], ['Whisky'], ['Scotch'], ['Brandy']]
l2 = (['Vodka', 'today', 'nice', 'drink', 'Scotch'], 'Group 2')

s1 = set()
s2 = set()

def listToSet(setx, listx):
for listobj in listx:
if type(listobj) == list:
listToSet(setx, listobj)
else:
setx.add(listobj)

listToSet(s1, l1)
listToSet(s2, l2)
print s1
print s2
print '/n'
print s1 & s2
thinkmore
2015-01-15 09:39:20 +08:00
遍历
scenix
2015-01-15 12:08:50 +08:00
递归试试?

#!/bin/env python
#encoding=utf-8
# Author: Aaron Shao - shao.dut@gmail.com
# Last modified: 2015-01-15 12:07
# Filename: test.py
# Description:

a= [['Vodka'], ['Whisky'], ['Scotch'], ['Brandy']]
b = (['Vodka', 'today', 'nice', 'drink', 'Scotch'], 'Group 2')

def parse(x):
if isinstance(x, (tuple,list)):
result = set([])
for i in x:
pass
result = result | parse(i)
return result
elif isinstance(x, str):
return set([x])
else:
return set([])

x = parse(a)
y = parse(b)

print x & y
scenix
2015-01-15 12:09:15 +08:00
妈蛋 忘了把email删了。。。
iannil
2015-01-15 12:14:05 +08:00
1、看list1到list2的难度有多大。
2、如果去掉无效元素难度不大,就直接先把list1都处理成list2,或把list1和list2都处理成list3的格式。
3、如果去掉无效元素难度过大,就反过来处理,把list1和list2中你需要的信息拿出来,而不是去掉没用的信息。相同的单词这种特征简直太好取了。
hahastudio
2015-01-15 12:54:13 +08:00
这时候就要祭出一个经典的 recipe 啦:
flatten arbitrarily nested lists
https://stackoverflow.com/questions/10823877/what-is-the-fastest-way-to-flatten-arbitrarily-nested-lists-in-python

交集就是
set(flatten(l1)).intersection(set(flatten(l2)))
imn1
2015-01-15 13:07:27 +08:00
二维表一向都交由 pandas/numpy 处理,相关函数多得是

虽然处理这个问题用 pandas 有点托大,但估计这种数据的产生和后续处理也有不少地方可以用到 pandas
meteor2013
2015-01-16 02:51:17 +08:00
@hahastudio 谢谢啊,你这个方法超赞!!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/162276

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX