自定义函数求list中的最大值和最小值

本文介绍了一个自定义函数findMinAndMax,该函数能够接收一个List作为参数,并返回这个List中的最大值和最小值。通过一系列测试案例验证了函数的正确性和有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义函数求list中的最大值和最小值

def findMinAndMax(L):
	if(len(L)==0):
	    return (None, None)  
	else:
	    min =L[0]
	    max =L[0]
	    for i in L:
	      if(i>max):
	        max=i
	      elif(i<min):
	        min=i
	    return (min,max)
	    
if findMinAndMax([]) != (None, None):
    print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
    print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
    print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
    print('测试失败!')
else:
    print('测试成功!')
<think>我们需要从QStringList中找出最大值最小值。注意,QStringList中的元素是字符串,但可能代表数字(整数或浮点数)或非数字。 如果列表中的字符串都是数字,我们可以将它们转换为数值类型(如int或double)然后比较。 如果列表中包含非数字字符串,我们需要决定如何处理:是跳过它们,还是报错,或者采用字符串比较(但字符串比较数值比较结果可能不同)。 根据需,我们通常有两种情况: 1. 列表中的字符串都是数值字符串,我们想要数值上的最大值最小值。 2. 我们想要字符串比较的最大值最小值(按字典序)。 这里我们假设需是数值比较,并且如果遇到非数字字符串,我们将其忽略,或者转换为0(或者根据需处理)。但是,如果列表中有非数字字符串,我们可能需要考虑是否要报错。 以下我们将提供两种方案: 方案1:数值比较(忽略非数字字符串) 方案2:字符串比较(按字典序) 同时,我们也可以考虑使用C++标准库算法Qt的迭代器。 由于QStringList是Qt中的字符串列表,我们可以使用循环遍历,或者使用STL算法(需要包含<algorithm>)Qt的转换函数。 下面分别给出代码示例:</think># 在 Qt 中获取 QStringList最大值最小值 在 Qt 中处理 `QStringList` 的最大值最小值时,需要根据字符串内容选择合适的比较方式。以下是几种常见场景的解决方案: ## 1. 数值比较(当字符串表示数字时) ```cpp #include <QStringList> #include <QDebug> #include <algorithm> #include <climits> void findMinMaxNumeric(const QStringList& list) { if (list.isEmpty()) { qWarning() << "List is empty!"; return; } // 方法1: 使用标准算法转换后比较 bool conversionOk = true; double minVal = std::numeric_limits<double>::max(); double maxVal = std::numeric_limits<double>::lowest(); QString minStr, maxStr; for (const QString& str : list) { bool ok; double val = str.toDouble(&ok); if (!ok) { qWarning() << "Invalid number:" << str; conversionOk = false; continue; } if (val < minVal) { minVal = val; minStr = str; } if (val > maxVal) { maxVal = val; maxStr = str; } } if (!conversionOk) { qWarning() << "Some values could not be converted to numbers"; } qDebug() << "Numeric Min:" << minStr << "(" << minVal << ")"; qDebug() << "Numeric Max:" << maxStr << "(" << maxVal << ")"; // 方法2: 使用 Qt 的排序功能(效率较低但简洁) QStringList sorted = list; std::sort(sorted.begin(), sorted.end(), [](const QString& a, const QString& b) { return a.toDouble() < b.toDouble(); }); qDebug() << "Sorted Min:" << sorted.first(); qDebug() << "Sorted Max:" << sorted.last(); } ``` ## 2. 字典序比较(字符串比较) ```cpp void findMinMaxLexicographic(const QStringList& list) { if (list.isEmpty()) { qWarning() << "List is empty!"; return; } // 方法1: 使用标准算法 QString minStr = *std::min_element(list.begin(), list.end()); QString maxStr = *std::max_element(list.begin(), list.end()); qDebug() << "Lexicographic Min:" << minStr; qDebug() << "Lexicographic Max:" << maxStr; // 方法2: 使用 Qt 的排序 QStringList sorted = list; sorted.sort(); qDebug() << "Sorted Min:" << sorted.first(); qDebug() << "Sorted Max:" << sorted.last(); } ``` ## 3. 自定义比较规则(考虑大小写、区域设置等) ```cpp void findMinMaxCustom(const QStringList& list) { if (list.isEmpty()) { qWarning() << "List is empty!"; return; } // 忽略大小写的比较 auto caseInsensitiveCompare = [](const QString& a, const QString& b) { return a.compare(b, Qt::CaseInsensitive) < 0; }; // 使用自定义比较函数 QString minStr = *std::min_element(list.begin(), list.end(), caseInsensitiveCompare); QString maxStr = *std::max_element(list.begin(), list.end(), caseInsensitiveCompare); qDebug() << "Case-Insensitive Min:" << minStr; qDebug() << "Case-Insensitive Max:" << maxStr; // 考虑本地化排序 QCollator collator; collator.setNumericMode(true); // 数字模式 collator.setCaseSensitivity(Qt::CaseInsensitive); QStringList sorted = list; std::sort(sorted.begin(), sorted.end(), collator); qDebug() << "Localized Sorted Min:" << sorted.first(); qDebug() << "Localized Sorted Max:" << sorted.last(); } ``` ## 4. 处理混合内容(数值字符串) ```cpp void findMinMaxMixed(const QStringList& list) { if (list.isEmpty()) { qWarning() << "List is empty!"; return; } // 分离数字文本 QStringList numericItems; QStringList textItems; for (const QString& item : list) { bool ok; item.toDouble(&ok); if (ok) { numericItems.append(item); } else { textItems.append(item); } } // 处理数字部分 if (!numericItems.isEmpty()) { QStringList sortedNumeric = numericItems; std::sort(sortedNumeric.begin(), sortedNumeric.end(), [](const QString& a, const QString& b) { return a.toDouble() < b.toDouble(); }); qDebug() << "Numeric Min:" << sortedNumeric.first(); qDebug() << "Numeric Max:" << sortedNumeric.last(); } // 处理文本部分 if (!textItems.isEmpty()) { QStringList sortedText = textItems; sortedText.sort(); qDebug() << "Text Min:" << sortedText.first(); qDebug() << "Text Max:" << sortedText.last(); } // 整体排序(数字视为文本) QStringList sortedAll = list; sortedAll.sort(); qDebug() << "Overall Min (as text):" << sortedAll.first(); qDebug() << "Overall Max (as text):" << sortedAll.last(); } ``` ## 5. 高效处理大型列表 ```cpp void findMinMaxEfficient(const QStringList& list) { if (list.isEmpty()) { qWarning() << "List is empty!"; return; } // 单次遍历算法(O(n)时间复杂度) QString minStr = list.first(); QString maxStr = list.first(); for (const QString& item : list) { if (item < minStr) minStr = item; if (item > maxStr) maxStr = item; } qDebug() << "Efficient Min:" << minStr; qDebug() << "Efficient Max:" << maxStr; // 使用并行算法(Qt Concurrent) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) auto [min, max] = QtConcurrent::blockingMappedReduced( list, [](const QString& item) { return item; }, [](QString& result, const QString& item) { if (item < result) result = item; }, QtConcurrent::OrderedReduce ); qDebug() << "Parallel Min:" << min; #endif } ``` ## 完整示例程序 ```cpp #include <QCoreApplication> #include <QStringList> #include <QDebug> #include <algorithm> #include <QtConcurrent> // 对于并行版本 int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); // 示例数据 QStringList fflList = { "42", "3.14", "-15", "1000", "apple", "Banana", "zebra", "0", "999", "Orange" }; qDebug() << "Original List:" << fflList; // 数值比较 qDebug() << "\n=== Numeric Comparison ==="; findMinMaxNumeric(fflList); // 字典序比较 qDebug() << "\n=== Lexicographic Comparison ==="; findMinMaxLexicographic(fflList); // 自定义比较 qDebug() << "\n=== Custom Comparison (Case-Insensitive) ==="; findMinMaxCustom(fflList); // 处理混合内容 qDebug() << "\n=== Mixed Content Handling ==="; findMinMaxMixed(fflList); // 高效方法 qDebug() << "\n=== Efficient Method ==="; findMinMaxEfficient(fflList); return 0; } ``` ## 输出解释 根据示例数据 `{"42", "3.14", "-15", "1000", "apple", "Banana", "zebra", "0", "999", "Orange"}`: 1. **数值比较**: - 最小值:`-15` - 最大值:`1000` 2. **字典序比较**: - 最小值:`"-15"`(因为 '-' 字符的ASCII码小于数字) - 最大值:`"zebra"` 3. **自定义比较(忽略大小写)**: - 最小值:`"apple"`(a在字母表中靠前) - 最大值:`"zebra"` 4. **混合内容处理**: - 数字部分最小值:`-15` - 数字部分最大值:`1000` - 文本部分最小值:`"Banana"`(因为B在Oz之前) - 文本部分最大值:`"zebra"` 5. **高效方法**: - 与字典序比较结果相同 ## 最佳实践建议 1. **明确比较需**: - 确定是需要数值比较还是字符串比较 - 考虑是否需要忽略大小写 - 是否需要本地化排序(使用 `QCollator`) 2. **错误处理**: - 检查列表是否为空 - 处理无效的数值转换 - 考虑混合内容的处理策略 3. **性能优化**: - 对于大型列表,使用单次遍历算法(O(n)复杂度) - 考虑使用并行算法(Qt Concurrent) - 避免不必要的排序(排序是 O(n log n) 复杂度) 4. **使用现代 C++ 特性**: ```cpp // C++17 结构化绑定 auto [min, max] = findMinMax(list); // Lambda 表达式 std::sort(list.begin(), list.end(), [](auto& a, auto& b) { return a.toDouble() < b.toDouble(); }); ``` 5. **Qt 特定优化**: ```cpp // 使用 QCollator 进行本地化排序 QCollator collator; collator.setNumericMode(true); std::sort(list.begin(), list.end(), collator); // 使用 Qt 算法 QString min = *std::min_element(list.cbegin(), list.cend()); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值