如何获取并匹配List1与List2对应值并输出指定格式结果?
解决方案
可以通过将两个列表对应元素配对后遍历输出的方式实现需求,以下是几种常见编程语言的实现示例:
Python 实现
List1 = ['A', 'B', 'C', 'D', 'E'] List2 = ['-', '-', '000123', '-', '000876'] # 配对两个列表并按格式输出 for item1, item2 in zip(List1, List2): print(f"{item1} has {item2}")
运行后输出结果:
A has - B has - C has 000123 D has - E has 000876
说明
zip(List1, List2)会把两个列表对应位置的元素打包成元组,比如('A', '-')、('C', '000123')等;- 循环遍历每一对元素,用f-string快速格式化出目标文本。
Java 实现
public class ListMatchOutput { public static void main(String[] args) { String[] List1 = {"A", "B", "C", "D", "E"}; String[] List2 = {"-", "-", "000123", "-", "000876"}; for (int i = 0; i < List1.length; i++) { System.out.println(List1[i] + " has " + List2[i]); } } }
内容的提问来源于stack exchange,提问作者QATester
相关产品推荐
相关产品推荐

