我正在尝试找到一种方法来打印列表中每个项目的位置。
例如:
example_lst = ['dog', 'cat', 'plant']
print(example_lst.index(*))
输出:
>>> ['dog, 0', 'cat, 1', 'plant, 2']
如果上面的例子令人困惑,我们深表歉意。
无论如何,我们将不胜感激!
答案 0 :(得分:3)
尝试紧凑列表理解:
[f'{v} {i}' for i, v in enumerate(example_lst)]
说明:
这将创建一个列表,其中每个元素由其中的for循环确定。
在此循环中,i
是循环中当前元素的索引,而v
是该元素的值。
for i, v in enumerate(example_lst)
然后将值和索引与
结合在一起f'{v} {i}'
这称为f字符串(格式化字符串)。
虽然这看起来令人困惑,但实际上非常简单。
F字符串提供了一种使用最小语法在字符串文字中嵌入表达式的方法。 source
要创建f字符串,只需在字符串之前放置f。然后将花括号中的所有内容都评估为python代码。
所以
f'{v} {i}'
根据循环所处的位置,简单地返回v + " " + i
,即“ dog 0”,“ cat 1”或“ plant 2”。
因此,您得到的结果是所需的。
['dog 0', 'cat 1', 'plant 2']
答案 1 :(得分:2)
您需要使用for loop
。 For循环遍历数组中的每个元素(除其他外),因此您可以通过以下方式轻松打印每个元素的索引:
example_lst = ['dog', 'cat', 'plant']
for item in example_lst:
print(example_lst.index(item))
在此示例中,item
在第一次迭代期间为“ dog”,在第二次迭代期间为“ cat”,而在第三次迭代期间为“ plant”。您也可以在更长的列表上使用它,因为for循环遍历整个列表。
但是您希望索引和项目同时显示。
要获得所需的格式,请使用enumerate
:
example_lst = ['dog', 'cat', 'plant']
new_list = []
for (index, item) in enumerate(example_lst): #enumerate allows us to access the element and index of a list at the same time
# Create a new list with the item and the index in each element
elem = str(item) + " " + str(index) # str() converts items to strings so they can be joined
new_list.append(elem)
print(new_list)
答案 2 :(得分:1)
def func(list):
ret = []
for pos, val in enumerate(list):
ret.append(f'{val}, {pos}')
return ret
您只需使用此函数即可构造一个新列表,然后将其返回。此功能所做的全部工作就是遍历数组中的元素,并简单地构造一个新列表,该列表包含位置值为逗号的字符串-然后返回该列表。希望这会有所帮助。
答案 3 :(得分:1)
您可以在列表推导中使用枚举内置函数,这将为您完成工作:
example = ['dog', 'cat', 'plant']
solution = [f"{value}, {key}" for key, value in enumerate(example)]
print(solution)
结果:
['dog, 0', 'cat, 1', 'plant, 2']
答案 4 :(得分:0)
example_lst = ['dog', 'cat', 'plant']
arr = []
for i, item in enumerate(example_lst):
arr.append(f"{item}, {i}")
print(arr)
输出:
['dog, 0', 'cat, 1', 'plant, 2']
答案 5 :(得分:0)
您可以使用列表理解和字符串格式来获得所需的结果。
import React, { useState } from "react";
import FormInput from "../Forminput/forminput";
import CustomButton from "../Custombutton/custombutton";
import axios from "axios";
const ProductUpload = () => {
const [sub_category, setSub_category] = useState({
sub_category: "",
});
const [product_name, setProduct_name] = useState({
product_name: "",
});
const [product_image, setProduct_image] = useState({
product_image: "",
});
const [product_specs, setProduct_specs] = useState({
product_specs: [{ specification: "", specvalue: "" }],
});
const imageSelectedHandler = (event) => {
setProduct_image({ product_image: event.target.files[0] });
};
// const imageUploadHandler = () => {
// const fd = new FormData();
// fd.append("product_image", product_image, product_image.name); //.name is Imp as name is property of file
// };
const handleChange = (i, e) => {
const { name, value } = e.target;
product_specs[i] = { ...product_specs[i], [name]: value };
setProduct_specs({ product_specs }); //TO BE CHECKED
};
//to add extra input field
const addClick = () => {
setProduct_specs({
product_specs: [...product_specs, { specification: "", specvalue: "" }],
});
};
//to remove extra input field
const removeClick = (i) => {
[product_specs].splice(i, 1);
setProduct_specs({
product_specs: [product_specs],
});
};
const handleSubmit = async (event) => {
event.preventDefault();
const newProduct = {
sub_category,
product_name,
product_image,
product_specs,
};
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const body = JSON.stringify(newProduct);
const res = await axios.post("/api/product", body, config);
console.log(res.data);
} catch (error) {
console.error(error.response.data);
}
};
const createUI = () => {
return [product_specs].map((el, i) => (
<div key={i} className="inputgroup">
<FormInput
type="text"
name="specification"
handleChange={handleChange}
value={el.specification}
label="specification"
required
customwidth="300px"
></FormInput>
<FormInput
type="text"
name="specvalue"
handleChange={handleChange}
value={el.specvalue}
label="specification values seperated by quomas"
required
></FormInput>
<CustomButton
onClick={removeClick(i)}
type="button"
value="remove"
style={{ margin: "12px" }}
>
Remove
</CustomButton>
</div>
));
};
return (
<div className="container">
<form
action="/upload"
method="post"
className="form"
onSubmit={handleSubmit}
encType="multipart/form-data"
>
<h3 style={{ color: "roboto, sans-serif" }}>
Add new product to the database
</h3>
<div
style={{
display: "flex",
height: "200px",
width: "200px",
border: "2px solid #DADCE0",
borderRadius: "6px",
position: "relative",
}}
>
<input
style={{ display: "none" }}
type="file"
accept="image/*"
onChange={imageSelectedHandler}
ref={(fileInput) => (this.fileInput = fileInput)}
multiple={false}
name="product_image"
/>
<CustomButton onClick={() => this.fileInput.click()}>
Select Image
</CustomButton>
<CustomButton
// onClick={imageUploadHandler}
>
Upload
</CustomButton>
{/*as per brad- type = "submit" value="submit" this should not be used, file should upload with the form submit */}
<div>
<img
style={{
width: "100%",
height: "100%",
}}
alt="#"
/>
</div>
</div>
<FormInput
type="text"
name="sub_category"
handleChange={handleChange}
value={sub_category}
label="select from subcategories"
required
></FormInput>
<FormInput
type="text"
name="product_name"
handleChange={handleChange}
value={product_name}
label="product name"
required
></FormInput>
{createUI()}
<div>
<CustomButton
onClick={addClick}
type="button"
style={{ margin: "14px" }}
>
Add More Fields
</CustomButton>
<CustomButton type="submit" style={{ margin: "12px" }}>
Upload Product
</CustomButton>
</div>
</form>
</div>
);
};
export default ProductUpload;
结果:
example_lst = ['dog', 'cat', 'plant']
li = [f"{it}, {i}" for i, it in enumerate(example_lst)]
print(li)
答案 6 :(得分:-1)
Choose:
打印0,因为dog在0位置(从0开始),而
^(?![^!?.\n\r]*[!?.])\w+:
打印2,因为“ plant”处于2位置。 对于您的问题,这会有所帮助。
example_lst = ['dog', 'cat', 'plant']
print(example_lst.index('dog'))
答案 7 :(得分:-1)
您可以使用enumerate
。举一个简单的例子(为简单起见,不考虑列表的理解):
example_lst = ['dog', 'cat', 'plant']
output = []
for idx, val in enumerate(example_lst):
output.append(f'{val}, {idx}')
print(output)
答案 8 :(得分:-1)
尝试一下:
example_lst = ['dog', 'cat', 'plant']
for i in example_lst:
print(i, '-', example_lst.index(i))