我正在通过从文本文件中逐行读取输入来在循环中编写一个具有if-else
条件的简单Python脚本。下面是我的脚本。
我应该得到预期的输出。请帮忙!
我的env.txt包含:
DEV01
DEV02
UAT01
UAT02
代码如下:
with open("env.txt") as envnames:
for eachenv in envnames:
if eachenv=="DEV01" or "DEV02":
eachenv="dev"
print (eachenv)
elif eachenv=="UAT01" or "UAT02":
eachenv="uat"
print(eachenv)
else :
print('')
预期:
dev
dev
uat
uat
实际:
dev
dev
dev
dev
答案 0 :(得分:6)
问题是if eachenv=="DEV01" or "DEV02"
。
您不能像这样检查。如果True
的结果将是eachenv=="DEV01"
,否则结果将是"DEV02"
,而不是False
。
你应该这样:
if eachenv in ["DEV01", "DEV02"]:
还将for eachenv in envnames:
更改为:
for eachenv in envnames.readlines():
答案 1 :(得分:3)
public class IntersectionOfTwoSets {
public class Point implements Comparable{
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Object o) {
if(this.x > ((Point)o).x) return 1;
if(this.x < ((Point)o).x) return -1;
if(this.y > ((Point)o).y) return 1;
if(this.y < ((Point)o).y) return -1;
return 0;
}
}
public Point[] intersectionOf(Point[] a, Point[] b) {
List<Point> result = new ArrayList<>();
Arrays.sort(a);
Arrays.sort(b);
for(int i = 0, j = 0; i < a.length && j < b.length; ) {
if(a[i].compareTo(b[j]) == 0) {
result.add(a[i]);
i++;
j++;
} else if (a[i].compareTo(b[j]) < 0) {
i ++;
} else {
j ++;
}
}
return (Point[])result.toArray();
}
表示以下情况之一:
if eachenv=="DEV01" or "DEV02":
等于eachenv
"DEV01"
那么"DEV02"
呢?它存在,因此条件的选项将是“真实的”,因此您的"DEV02"
将始终通过。
这不是链接条件的工作方式。
您的意思是:
if
现在是以下情况之一:
if eachenv=="DEV01" or eachenv=="DEV02":
等于eachenv
"DEV01"
等于eachenv
是的!
答案 2 :(得分:2)
在if eachenv=="DEV01" or "DEV02":
行中,第二个条件始终为true:
>>> if "DEV02":
... print('hello')
...
hello
发生这种情况是因为字符串"DEV02"
是一个对象,因此将被求值True
。
@Lightness Races in Orbit提供了编写此if语句的正确方法。