如何将两个数组合并为带固定句式的新字符串数组
Hey there! Combining your authors and books arrays into a list of strings like "Tolstoy wrote War and Peace." is totally doable with some simple array traversal logic. Let's break down how to do this in a few popular programming languages:
The map() method is perfect here—it lets you iterate over the authors array while accessing the corresponding index in books:
const authors = ["Tolstoy", "Orwell", "Rowling"]; const books = ["War and Peace", "1984", "Harry Potter and the Philosopher's Stone"]; // Use map to pair each author with their book const result = authors.map((author, index) => `${author} wrote ${books[index]}.`); console.log(result); // Output: ["Tolstoy wrote War and Peace.", "Orwell wrote 1984.", "Rowling wrote Harry Potter and the Philosopher's Stone."]
A quick note: Make sure both arrays are the same length—if one is longer, you'll get undefined for the mismatched positions.
Python's zip() function is made for pairing elements from multiple iterables. Combine it with a list comprehension for a clean solution:
authors = ["Tolstoy", "Orwell", "Rowling"] books = ["War and Peace", "1984", "Harry Potter and the Philosopher's Stone"] # Zip the arrays and build each string with an f-string result = [f"{author} wrote {book}." for author, book in zip(authors, books)] print(result) # Output: ['Tolstoy wrote War and Peace.', 'Orwell wrote 1984.', "Rowling wrote Harry Potter and the Philosopher's Stone."]
zip() will stop at the shorter array if lengths don't match—if you need to handle mismatched lengths, you can use itertools.zip_longest instead.
For Java, a simple for loop with index checking works great (to avoid array out-of-bounds errors):
import java.util.ArrayList; import java.util.List; public class AuthorBookMatcher { public static void main(String[] args) { String[] authors = {"Tolstoy", "Orwell", "Rowling"}; String[] books = {"War and Peace", "1984", "Harry Potter and the Philosopher's Stone"}; List<String> result = new ArrayList<>(); // Ensure arrays are the same length before processing if (authors.length == books.length) { for (int i = 0; i < authors.length; i++) { result.add(authors[i] + " wrote " + books[i] + "."); } } System.out.println(result); // Output: [Tolstoy wrote War and Peace., Orwell wrote 1984., Rowling wrote Harry Potter and the Philosopher's Stone.] } }
Adding the length check is a good practice to prevent runtime errors if the arrays aren't properly aligned.
If your original code was failing, chances are it wasn't correctly pairing indices (like using a loop that didn't track the position across both arrays) or using the wrong method for combining elements. These examples should fix that!
内容的提问来源于stack exchange,提问作者Lucas Smallwood

