sorted(by: { (a, b) -> Bool in

本文介绍了如何在Swift中使用sorted方法对数组和字典进行排序,通过闭包自定义排序规则。首先展示了如何对整数数组进行倒置排序,接着讲解了如何根据字典值对学生姓名进行升序排序。

swift数组sorted排序

这个没有找到具体的说明,不过我的理解嘛就是任意有序的俩元素a 和 b进行比较,都满足于return后面的关系。

var arrayOri2 = Array<Int>()
// 给数组赋初值
for index in 0...9{
    arrayOri2.append(index)
}
print(arrayOri2)
// 进行倒置排序
arrayOri2 = arrayOri2.sorted(by: { (a, b) -> Bool in
    return a>b
})
print(arrayOri2)

// 字典的排序
var dicOri4 = ["王晓":98,"邹明":86,"李小伟":93]
for item in dicOri4.sorted(by: { (student1, student2) -> Bool in
    return student1.value > student2.value
}){
    print(item)
}

若是不对还请纠正。

--------------------------------------------------------------------------- TokenizationError Traceback (most recent call last) File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/tokenize.py:210, in normalize_object(o) 209 try: --> 210 return _normalize_pickle(o) 211 except Exception: File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/tokenize.py:257, in _normalize_pickle(o) 256 if pik is None: --> 257 _maybe_raise_nondeterministic("Failed to tokenize deterministically") 258 pik = int(uuid.uuid4()) File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/tokenize.py:89, in _maybe_raise_nondeterministic(msg) 88 if val or val is None and config.get("tokenize.ensure-deterministic"): ---> 89 raise TokenizationError(msg) TokenizationError: Failed to tokenize deterministically During handling of the above exception, another exception occurred: TokenizationError Traceback (most recent call last) Cell In[89], line 6 3 start_time = time.time() 5 # 模拟执行代码 ----> 6 hold_data() 8 # 获取程序结束时间 9 end_time = time.time() Cell In[61], line 48, in hold_data() 46 dddf = process_partition(df,df.columns,nul_columns, param.get('nullValues')) 47 # dddf = calculate_non_null_ratio(df,df.columns) ---> 48 print(dddf.compute()) File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/base.py:373, in DaskMethodsMixin.compute(self, **kwargs) 349 def compute(self, **kwargs): 350 """Compute this dask collection 351 352 This turns a lazy Dask collection into its in-memory equivalent. (...) 371 dask.compute 372 """ --> 373 (result,) = compute(self, traverse=False, **kwargs) 374 return result File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/base.py:678, in compute(traverse, optimize_graph, scheduler, get, *args, **kwargs) 659 expr = FinalizeCompute(expr) 661 with shorten_traceback(): 662 # The high level optimize will have to be called client side (for now) 663 # The optimize can internally trigger already a computation (...) 675 # change the graph submission to a handshake which introduces all sorts 676 # of concurrency control issues) --> 678 expr = expr.optimize() 679 keys = list(flatten(expr.__dask_keys__())) 681 results = schedule(expr, keys, **kwargs) File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/_expr.py:437, in Expr.optimize(self, fuse) 434 def optimize(self, fuse: bool = False) -> Expr: 435 stage: OptimizerStage = "fused" if fuse else "simplified-physical" --> 437 return optimize_until(self, stage) File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/_expr.py:931, in optimize_until(expr, stage) 928 return result 930 # Simplify --> 931 expr = result.simplify() 932 if stage == "simplified-logical": 933 return expr File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/_expr.py:447, in Expr.simplify(self) 445 while True: 446 dependents = collect_dependents(expr) --> 447 new = expr.simplify_once(dependents=dependents, simplified={}) 448 if new._name == expr._name: 449 break File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/_expr.py:417, in Expr.simplify_once(self, dependents, simplified) 414 if isinstance(operand, Expr): 415 # Bandaid for now, waiting for Singleton 416 dependents[operand._name].append(weakref.ref(expr)) --> 417 new = operand.simplify_once( 418 dependents=dependents, simplified=simplified 419 ) 420 simplified[operand._name] = new 421 if new._name != operand._name: File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/_expr.py:417, in Expr.simplify_once(self, dependents, simplified) 414 if isinstance(operand, Expr): 415 # Bandaid for now, waiting for Singleton 416 dependents[operand._name].append(weakref.ref(expr)) --> 417 new = operand.simplify_once( 418 dependents=dependents, simplified=simplified 419 ) 420 simplified[operand._name] = new 421 if new._name != operand._name: [... skipping similar frames: Expr.simplify_once at line 417 (2943 times)] File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/_expr.py:417, in Expr.simplify_once(self, dependents, simplified) 414 if isinstance(operand, Expr): 415 # Bandaid for now, waiting for Singleton 416 dependents[operand._name].append(weakref.ref(expr)) --> 417 new = operand.simplify_once( 418 dependents=dependents, simplified=simplified 419 ) 420 simplified[operand._name] = new 421 if new._name != operand._name: File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/_expr.py:390, in Expr.simplify_once(self, dependents, simplified) 387 expr = self 389 while True: --> 390 out = expr._simplify_down() 391 if out is None: 392 out = expr File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/dataframe/dask_expr/_expr.py:1977, in Assign._simplify_down(self) 1974 if self._check_for_previously_created_column(self.frame): 1975 # don't squash if we are using a column that was previously created 1976 return -> 1977 return Assign(*self._remove_common_columns(self.frame)) 1978 elif isinstance(self.frame, Projection) and isinstance( 1979 self.frame.frame, Assign 1980 ): 1981 if self._check_for_previously_created_column(self.frame.frame): File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/_expr.py:875, in SingletonExpr.__new__(cls, _determ_token, *args, **kwargs) 873 if not hasattr(cls, "_instances"): 874 cls._instances = weakref.WeakValueDictionary() --> 875 inst = super().__new__(cls, *args, _determ_token=_determ_token, **kwargs) 876 _name = inst._name 877 if _name in cls._instances and cls.__init__ == object.__init__: File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/_expr.py:72, in Expr.__new__(cls, _determ_token, *args, **kwargs) 69 inst.operands = [_unpack_collections(o) for o in operands] 70 # This is typically cached. Make sure the cache is populated by calling 71 # it once ---> 72 inst._name 73 return inst File ~/.conda/envs/py311/lib/python3.11/functools.py:1001, in cached_property.__get__(self, instance, owner) 999 val = cache.get(self.attrname, _NOT_FOUND) 1000 if val is _NOT_FOUND: -> 1001 val = self.func(instance) 1002 try: 1003 cache[self.attrname] = val File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/dataframe/dask_expr/_expr.py:604, in Blockwise._name(self) 602 else: 603 head = funcname(type(self)).lower() --> 604 return head + "-" + self.deterministic_token File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/_expr.py:538, in Expr.deterministic_token(self) 533 @property 534 def deterministic_token(self): 535 if not self._determ_token: 536 # Just tokenize self to fall back on __dask_tokenize__ 537 # Note how this differs to the implementation of __dask_tokenize__ --> 538 self._determ_token = self.__dask_tokenize__() 539 return self._determ_token File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/_expr.py:147, in Expr.__dask_tokenize__(self) 141 def __dask_tokenize__(self): 142 if not self._determ_token: 143 # If the subclass does not implement a __dask_tokenize__ we'll want 144 # to tokenize all operands. 145 # Note how this differs to the implementation of 146 # Expr.deterministic_token --> 147 self._determ_token = _tokenize_deterministic(type(self), *self.operands) 148 return self._determ_token File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/tokenize.py:457, in _tokenize_deterministic(*args, **kwargs) 455 def _tokenize_deterministic(*args, **kwargs) -> str: 456 # Utility to be strict about deterministic tokens --> 457 return tokenize(*args, ensure_deterministic=True, **kwargs) File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/tokenize.py:76, in tokenize(ensure_deterministic, *args, **kwargs) 74 token = _ENSURE_DETERMINISTIC.set(ensure_deterministic) 75 try: ---> 76 return _tokenize(*args, **kwargs) 77 finally: 78 if token: File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/tokenize.py:34, in _tokenize(*args, **kwargs) 33 def _tokenize(*args: object, **kwargs: object) -> str: ---> 34 token: object = _normalize_seq_func(args) 35 if kwargs: 36 token = token, _normalize_seq_func(sorted(kwargs.items())) File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/tokenize.py:154, in _normalize_seq_func(seq) 152 _SEEN[id(seq)] = len(_SEEN), seq 153 try: --> 154 return tuple(map(_inner_normalize_token, seq)) 155 finally: 156 del _SEEN[id(seq)] File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/tokenize.py:147, in _normalize_seq_func.<locals>._inner_normalize_token(item) 145 if isinstance(item, _IDENTITY_DISPATCH): 146 return item --> 147 return normalize_token(item) File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/tokenize.py:212, in normalize_object(o) 210 return _normalize_pickle(o) 211 except Exception: --> 212 _maybe_raise_nondeterministic( 213 f"Object {o!r} cannot be deterministically hashed. This likely " 214 "indicates that the object cannot be serialized deterministically." 215 ) 216 return uuid.uuid4().hex File ~/.conda/envs/py311/lib/python3.11/site-packages/dask/tokenize.py:89, in _maybe_raise_nondeterministic(msg) 87 val = None 88 if val or val is None and config.get("tokenize.ensure-deterministic"): ---> 89 raise TokenizationError(msg) TokenizationError: Object <class 'dask.dataframe.dask_expr._expr.Assign'> cannot be deterministically hashed. This likely indicates that the object cannot be serialized deterministically.
08-29
#include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <string> using namespace std; // 元器件结构体 struct Component { string id; // 编号(如CON00001) string name; // 名称 int inCount; // 入库数量 int outCount; // 出库数量 // 计算当前库存(入库-出库) int getStock() const { return inCount - outCount; } }; vector<Component> components; // 存储所有元器件信息 const string FILE_PATH = "C:\\Users\\o1306\\Desktop\\1\\2.txt"; // 修改后的文件路径 // 0. 功能菜单 void showMenu() { cout << "\n==== 电子实验室元器件库存管理系统 ====\n"; cout << "0. 显示菜单\n"; cout << "1. 读取/录入元器件信息\n"; cout << "2. 查找元器件信息\n"; cout << "3. 删除(出库)元器件\n"; cout << "4. 修改元器件信息\n"; cout << "5. 新增(新购)元器件\n"; cout << "6. 统计库存信息\n"; cout << "7. 退出系统\n"; cout << "请选择功能(0-7):"; } // 1. 读取/录入信息(支持文件读取和键盘录入) void readOrInputComponents() { int choice; cout << "1. 从文件读取(文件路径:" << FILE_PATH << ")\n"; cout << "2. 键盘录入新数据\n"; cout << "请选择:"; cin >> choice; if (choice == 1) { ifstream file(FILE_PATH); if (!file) { cout << "错误:文件不存在!\n"; return; } Component c; while (file >> c.id >> c.name >> c.inCount >> c.outCount) { components.push_back(c); } file.close(); cout << "文件读取成功,当前数据量:" << components.size() << "\n"; } else if (choice == 2) { Component c; cout << "请输入元器件编号:"; cin >> c.id; cout << "请输入名称:"; cin >> c.name; cout << "请输入入库数量:"; cin >> c.inCount; cout << "请输入出库数量:"; cin >> c.outCount; components.push_back(c); cout << "录入成功!\n"; } } // 按编号查找元器件(返回迭代器,未找到返回end()) vector<Component>::iterator findComponentByID(string id) { return find_if(components.begin(), components.end(), [&](const Component& c) { return c.id == id; }); } // 2. 查找功能 void searchComponent() { if (components.empty()) { cout << "当前无库存数据,请先录入!\n"; return; } string id; cout << "请输入要查找的元器件编号:"; cin >> id; auto it = findComponentByID(id); if (it != components.end()) { cout << "编号:" << it->id << "\n"; cout << "名称:" << it->name << "\n"; cout << "入库数量:" << it->inCount << "\n"; cout << "出库数量:" << it->outCount << "\n"; cout << "当前库存:" << it->getStock() << "\n"; } else { cout << "未找到编号为 " << id << " 的元器件!\n"; } } // 3. 删除(出库)元器件 void deleteComponent() { if (components.empty()) { cout << "当前无库存数据,请先录入!\n"; return; } string id; cout << "请输入要删除(出库)的元器件编号:"; cin >> id; auto it = findComponentByID(id); if (it != components.end()) { int outNum; cout << "请输入本次出库数量(当前库存:" << it->getStock() << "):"; cin >> outNum; if (outNum > it->getStock()) { cout << "出库数量超过库存,操作失败!\n"; return; } it->outCount += outNum; // 累计出库(不直接删除,保留记录) cout << "出库成功,当前库存:" << it->getStock() << "\n"; } else { cout << "未找到该元器件,删除失败!\n"; } } // 4. 修改元器件信息 void updateComponent() { if (components.empty()) { cout << "当前无库存数据,请先录入!\n"; return; } string id; cout << "请输入要修改的元器件编号:"; cin >> id; auto it = findComponentByID(id); if (it != components.end()) { cout << "当前信息:\n"; cout << "编号:" << it->id << "\n"; cout << "名称:" << it->name << "\n"; cout << "入库数量:" << it->inCount << "\n"; cout << "出库数量:" << it->outCount << "\n"; cout << "请输入新名称(留空不修改):"; string newName; cin >> newName; if (!newName.empty()) it->name = newName; cout << "请输入新入库数量(-1不修改):"; int newIn; cin >> newIn; if (newIn != -1) it->inCount = newIn; cout << "请输入新出库数量(-1不修改):"; int newOut; cin >> newOut; if (newOut != -1) it->outCount = newOut; cout << "修改成功!\n"; } else { cout << "未找到该元器件,修改失败!\n"; } } // 5. 新增(新购)元器件 void addNewComponent() { Component c; cout << "请输入新元器件编号(需唯一):"; cin >> c.id; // 检查编号是否重复 if (findComponentByID(c.id) != components.end()) { cout << "编号已存在,新增失败!\n"; return; } cout << "请输入名称:"; cin >> c.name; cout << "请输入入库数量(新购默认入库):"; cin >> c.inCount; c.outCount = 0; // 新购未出库 components.push_back(c); cout << "新增成功!\n"; } // 6. 统计库存信息 void statisticsInventory() { if (components.empty()) { cout << "当前无库存数据,请先录入!\n"; return; } cout << "==== 库存统计 ====\n"; cout << "总元器件数量:" << components.size() << "\n"; cout << "按库存排序(从高到低):\n"; // 排序并输出 vector<Component> sorted = components; sort(sorted.begin(), sorted.end(), [](const Component& a, const Component& b) { return a.getStock() > b.getStock(); }); for (const auto& c : sorted) { cout << "编号:" << c.id << " 名称:" << c.name << " 库存:" << c.getStock() << "\n"; } } // 7. 退出系统(保存数据到文件) void saveAndExit() { ofstream file(FILE_PATH); if (!file) { cout << "错误:无法写入文件!\n"; return; } for (const auto& c : components) { file << c.id << " " << c.name << " " << c.inCount << " " << c.outCount << "\n"; } file.close(); cout << "数据已保存到" << FILE_PATH << ",系统退出。\n"; } int main() { int choice; showMenu(); // 首次显示菜单 while (cin >> choice) { switch (choice) { case 0: showMenu(); break; case 1: readOrInputComponents(); break; case 2: searchComponent(); break; case 3: deleteComponent(); break; case 4: updateComponent(); break; case 5: addNewComponent(); break; case 6: statisticsInventory(); break; case 7: saveAndExit(); return 0; default: cout << "无效选择,请重新输入(0-7)!\n"; } showMenu(); // 每次操作后重新显示菜单 } return 0; }
06-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值