We will write a procedure every-nth that accepts two arguments: num is an integer and list-of-sents is a list of a certain number of lists. every-nth selects the num-th elements from each list in list-of-sents and returns the list of selected elements. Assume that all lists in listof-sents have more than num elements.
时间: 2023-11-22 12:55:44 浏览: 42
Here's a possible implementation of the every-nth procedure in Python:
```python
def every_nth(num, list_of_sents):
result = []
for sentence in list_of_sents:
result.append(sentence[num-1])
return result
```
The procedure takes the `num` argument and the `list_of_sents` argument. It initializes an empty list called `result` to store the selected elements. It then loops through each sentence in the `list_of_sents` and appends the `num`-th element (i.e., the element at index `num-1`) to the `result` list. Finally, it returns the `result` list.
Here's an example usage of the every-nth procedure:
```python
list_of_sents = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
selected_elements = every_nth(2, list_of_sents)
print(selected_elements) # Output: ['b', 'e', 'h']
```
In this example, we call the every-nth procedure with `num=2` and `list_of_sents=[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]`. The procedure selects every second element from each sub-list in `list_of_sents`, resulting in the list `['b', 'e', 'h']`.