我正在编写大量代码,我希望缩短or
长度表达式。
假设我们有一个列表,例如:
farm = ["cow","cow","cow", "hen","hen","hen", "fox","fox","fox", "hen","hen", "hen"]
lookup = ["cow","hen"]
我应该检查lookfor
列表中farm
是否有三个连续元素。
一种方法是:
for i in range (0,len(farm) - 2):
if ((farm[i] == farm[i+1] == farm[i+2] == lookup[0])
or (farm[i] == farm[i+1] == farm[i+2] == lookup[1])):
# do something
现在,如果lookup
中的元素数量很少,则可以按上述方式编写。但是,如果它太长,代码看起来很麻烦并且难以维护。是否有更简洁的编写代码的方式,可能是列表理解格式 - 这样我就不必手动编写来查找lookup
的所有元素?
答案 0 :(得分:2)
试试这个
class SFProfileViewController: UIViewController, UITableViewDelegate {
@IBOutlet weak var nameLabelTwo: UILabel!
var user: User?
var userList = [User]()
@IBOutlet weak var imageOne: UIImageView!
var imageURL: String?
var imageOneUrl: String!
var nameProfile : String!
var locationProfile: String!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
print(locationProfile)
print(nameProfile)
print(imageOneUrl)
imageOne.image = UIImage(named: imageOneUrl)
nameLabelTwo.text = String(describing: nameProfile!)
nameLabel.text = String(describing: nameProfile!)
locationLabel.text = String(describing: locationProfile!)
}
将检查确切的三个连续键。对于至少三个,您可以按大小过滤组,并检查每个条目是否在查找中。
答案 1 :(得分:1)
未经测试,但“像这样”;-)应该有效。 int arr[] = {1,2};
Object o = arr;
Object o1 = new int[2];
Object o2 = new int[]{1,2};
Object o3 = {1,2};
是处理任意数量any()
s的自然方式,or
是任意数量的all()
s。
and
if any(farm[i] == farm[i+1] == farm[i+2] == target for i in range(len(farm) - 2)
for target in lookup):
# do something
此变体将为您提供匹配的i
值,与您的原始代码非常相似:
i