python - 使用列表列表并进行一些比较 Python
问题描述
我不知道如何比较 2 个不同的列表并写下我需要的内容:我有一个列表。我需要检查 3 件事。首先,如果item[1], item[2]
ofeste_mes
item
在列表中resto
并将完整添加item
到changes
. 其次,如果item[1], item[2]
ofeste_mes
item
不在 the 中resto
,添加到news
和 for the item[1], item[2]
of resto
item
are not este_mes
,添加到lost
este_mes = [
['1', 'A', 'a', '300'],
['1', 'B', 'b', '30'],
['1', 'C', 'c', '100'],
['1', 'D', 'd', '4500']]
resto = [
['2', 'A', 'a', '3'],
['2', 'B', 'b', '302'],
['2', 'X', 'x', '98'],
['2', 'Z', 'z', '276'],
['3', 'A', 'a', '54'],
['3', 'B', 'b', '65'],
['3', 'F', 'f', '76'],
['3', 'Y', 'y', '99']]
# I need something like this but I don't know how can I do it!
changes = []
news = []
lost = []
for item in este_mes:
if item[1] and item[2] are in some item of resto:
changes.append(item_resto)
if item[1] and item[2] are not in some item of resto:
news.append(item)
for item in resto:
if item[1] and item[2] are not in item of este_mes:
lost.append(item_resto)
答案应该是:
news = [['1', 'C', 'c', '100'],
['1', 'D', 'd', '4500']]
lost = [['2', 'X', 'x', '98'],
['2', 'Z', 'z', '276'],
['3', 'F', 'f', '76'],
['3', 'Y', 'y', '99']]
changes = [['2', 'A', 'a', '3'],
['2', 'B', 'b', '302'],
['3', 'A', 'a', '54'],
['3', 'B', 'b', '65']]
这是答案:
este_mes = []
resto = []
changes = []
for item in este_mes:
for rest in resto:
if (item[1] == rest[1] and item[2] == rest[2]):
rest = [rest[0]] + [item[1]] + [item[2]] + ([float(item[3]) - float(rest[3])])
changes.append(rest)
resto.remove(rest)
解决方案
我已经评论了代码,所以希望你能遵循逻辑。
#initialise our lists
news = []
changes = []
lost = []
#iterate over each list in `este_mes`
for l in este_mes:
#matches marks whether we have matched in `resto`
matched = False
for ll in resto:
if l[1] == ll[1] and l[2] == ll[2]:
#we matched, so append list from `resto` to changes
changes.append(ll)
matched = True
#if there were no matches, append the `este_mes` list to `news`
if not matched:
news.append(l)
#iterate over lists in `resto` to look for ones to add to `lost`
for l in resto:
#check to see if there are any matches in `este_mes`
for ll in este_mes:
if l[1] == ll[1] and l[2] == ll[2]:
break
else:
#this `else` clause is run if there was no `break` -
#indicates that no matches were found so add to `lost`.
lost.append(l)
输出正确的列表:
>>> news
[['1', 'C', 'c', '100'], ['1', 'D', 'd', '4500']]
>>> lost
[['2', 'X', 'x', '98'], ['2', 'Z', 'z', '276'], ['3', 'F', 'f', '76'], ['3', 'Y', 'y', '99']]
>>> changes
[['2', 'A', 'a', '3'], ['3', 'A', 'a', '54'], ['2', 'B', 'b', '302'], ['3', 'B', 'b', '65']]
推荐阅读
- excel - 为每个选定的 Excel 工作表创建一个 pdf
- c# - 按下向上或向下箭头键时 WPF ComboBox PreviewKeyDown 不会出现
- spring-boot - 将 spring-data-commons 从 1.12.10.RELEASE 升级到 1.13.12.RELEASE 抛出错误
- ios - 以编程方式快速擦除 iPhone 的数据
- javascript - 根据先前的选择下拉选择动态填充选择下拉列表并验证
- python - 在特定日期使用 R 下载 Azure Blob 容器
- javascript - 在处理应用程序的两个 html 页面之间的自定义事件时出现问题
- asp.net - Heroku dotnet core - libunwind.so.8:无法打开共享对象 - 显然是常见问题
- java - 从 C# 日期到 Java 日期,将 Long 转换为 DateTime
- javascript - 如何在onclick下划线并添加到textarea