python - 如何检查某些列表是否正好有两个值并且在某些范围内?
问题描述
我有一个文件:
A1=[0.65,0.64,1.01]
A2=[1.13,1.21]
A3=[0.75,1.11]
A4=[]
A5=[0.65]
A6=[0.95,1.83]
如果六个列表中至少有两个恰好有两个值(从 0 到 3 个值),并且 0.45<=values<1.4,则打印“A=True” 在这种情况下,A2,A3 有两个值,而 A2 的值,A3 在 [0.6,1.4] 之间,所以这是真的。
我试过这样的:
alist=[A1,A2,A3,A4,A5,A6]
blist=[]
y=[]
for row in alist:
def two_value(alist):
for i in alist:
if len(i)==2:
blist.append(i)
return False
#I will get three list True
#if len(blist) >=2:
#check the blist if they are among the range of [0.6,1.4]
def range(blist):
for ls in blist:
for i in ls:
x =all(1.4>=i>=0.6 for i in ls.split(','))
y.append(x)
我对python不熟悉,请问有没有办法在python或者bash中实现这个?</p>
解决方案
您的输入文件如下所示:
A1=[0.65,0.64,1.01]
A2=[1.13,1.21]
A3=[0.75,1.11]
A4=[]
A5=[0.65]
A6=[0.95,1.83]
假设数据在foo.txt
. 首先,让我们获取一个文件句柄:
results = {}
with open("foo.txt", "r") as f:
...
我们现在要遍历文件的行,依次处理每一行。对于我们处理的每一行,我们将检查:
它有两个元素吗?
两个元素都在 [i, j] 范围内吗?
因为列表必须同时为真才能通过,所以只要我们知道任一条件不满足,我们就应该停止处理一行。
首先,让我们在分隔符 ( ) 上分割每一行=
:
results = {}
with open("foo.txt", "r") as f:
for line in f:
try:
key, value = line.split("=") # This is called "unpacking".
except ValueError:
# If we don't have enough values to unpack, then = isn't
# in the line: skip it.
continue
接下来,让我们使用json.loads
将每个 JSON 编码的字符串数组放入数字列表中。一旦我们有了一个列表,我们就可以检查它的长度:如果它大于两个,它就不能成为候选,所以我们继续。
import json
results = {}
with open("foo.txt", "r") as f:
for line in f:
try:
key, value = line.split("=") # This is called "unpacking".
except ValueError:
continue
l = json.loads(value.strip())
if len(l) != 2:
continue
接下来,让我们检查列表中的所有元素是否都在所需的范围内。如果是,我们会跟踪该列表。否则,我们什么也不做。
import json
results = {}
with open("foo.txt", "r") as f:
for line in f:
try:
key, value = line.split("=") # This is called "unpacking".
except ValueError:
continue
l = json.loads(value.strip())
if len(l) != 2:
continue
# This type of check is O(n), but we KNOW l has exactly
# two elements, so it should be OK.
if all(val >= 0.6 and val <= 1.4 for val in l):
results[key] = l
# If we have at least one result, print it.
if results:
print(results)
推荐阅读
- asp.net - 使用节点 js 的 ASP NET MVC Web 部署(发布)预览 - 错误日志
- android - 用于获取有关国家地区(州)信息的 API
- c++ - 具有移动和复制语义的构造函数
- python - 最初未在python中分配时将变量存储在列表中
- javascript - 如何使用 for 循环发出多个 AJAX 请求
- python - 如何获取 CSV 中的所有数据
- spring-aop - Spring AOP - 从 GetMapping 中获取价值
- nativescript - 如何让用户在 nativescript 中选择要上传的文件(尝试了 nativescript-imagepicker 但也需要非图像)
- c++ - 错误:ISO C++ 禁止从字符串常量转换为 char*
- sabre - 找不到元素“DailySalesReportRQ”的声明